Skip to main content
 首页 » 编程设计

python之我怎样才能提高这个 Gamma 函数和复数相关代码的速度

2025年05月04日12lautakyan007

Context: I am trying to make a very simple gamma function fractal plotting using Python and sympy, initially a very simple version to understand how it works (two mapping colors based on the value of counter=0 or 1).

基本上,代码(下面)调用 gamma 函数,然后进行一些复数比较:只检查复数“nextcomplex=gamma(mycomplex)”是否比初始的“mycomplex”更接近“1+0i” “复数。制作分形的最终算法比这更复杂,但基本计算与那些类似,所以我需要提高这个简单代码的速度。

对于小间隔它工作正常,我可以绘制值,但对于大间隔非常慢,我现在正在运行它并且它超过 1 小时并且仍在运行总共 test_limitn x test_limitm=1000x1000 个元素. (例如,高达 100x100 就可以了,我可以绘制这些值并看到一个非常基本的分形)

My question is: how could I enhance the code to make it faster? (e.g. other Python libraries, or there are other functions much better to do the comparisons, etc.)

from sympy import gamma,I,re,im,zoo 
test_limitn = 1000 
test_limitm = 1000 
for m in range(-test_limitm,test_limitm): 
    for n in range(-test_limitn, test_limitn):           
        counter = 0 
        mycomplex = m+(n*I) 
        nextcomplex = gamma(mycomplex).evalf(1)  
        if mycomplex!=zoo and nextcomplex!=zoo: 
            absrenextcomplex = re(nextcomplex) 
            absimnextcomplex = abs(im(nextcomplex)) 
 
            if (abs(n) > absimnextcomplex) and (abs(1-m) > abs(1-absrenextcomplex)): 
                counter = 1 

非常欢迎任何提示,谢谢!

请您参考如下方法:

如果您只是用数字来做事,那么使用像 NumPy 这样的数字库会更好。 SymPy 专为符号计算而设计,虽然它可以执行数值计算,但速度不是很快。

除此之外,numba 还可以提高循环的性能。