为什么numpy.arange和range生成的相同数字的复数函数不同?

问题描述

# necessary imports
import numpy as np
import matplotlib.pyplot as plt

可复制的设置

Binet公式来自here

enter image description here

让我们在python中定义此函数

def binet(n):
    phi = (1 + 5 ** 0.5) / 2
    return ((phi**n) - (-1/phi)**n) / (5**0.5)

对于phi值,我使用了this


工作原理

让我们为binet(n)计算n=[0.1,0.2,0.3,0.4,0.5,...,4.9,5.0]

[binet(x/10) for x in range(1,51)]

让我们来绘制它:

# our results
plt.plot([n.real for n in binetn],[n.imag for n in binetn])
# classic fibonacci numbers
plt.scatter([1,1,3,5],[0,0],c='r')

enter image description here

看起来不错,同意this和我们的数学知识。


什么不起作用

基于上述情况,我确信这也将起作用:

binetn=[binet(x) for x in np.arange(0.1,5.1,0.1)]

但是,不是。 binetn变为:

[nan,nan,1.0,5.000000000000001]

就是nan,除非binet(n)是真实的。

它还会发出警告:

/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:2: RuntimeWarning:在double_scalars中遇到无效值


问题

为什么我不能遍历range()生成的数字列表并得到复杂的结果,而我却不能对np.arange()做同样的事情?

解决方法

重复项着重于np.arange。但这不是这里的问题。

比较将浮点数传递到binetnp.float64

In [52]: binet(0.1)                                                                                  
Out[52]: (0.06391735396852471-0.13170388861716523j)
In [53]: binet(np.float64(0.1))                                                                      
/usr/local/bin/ipython3:3: RuntimeWarning: invalid value encountered in double_scalars
  # -*- coding: utf-8 -*-
Out[53]: nan

或这些迭代:

In [54]: [binet(float(x)) for x in np.arange(0.1,5.1,0.1)];                                        
In [55]: [binet(x) for x in np.arange(0.1,0.1).tolist()];                                      
In [56]: [binet(x) for x in np.arange(0.1,0.1)];                                               
/usr/local/bin/ipython3:3: RuntimeWarning: invalid value encountered in double_scalars
  # -*- coding: utf-8 -*-

进一步挖掘,它似乎与complex有关。如果numpy参数很复杂,则计算可以:

In [58]: binet(np.complex(.1))                                                                       
Out[58]: (0.06391735396852471-0.13170388861716523j)
In [59]: [binet(x) for x in np.arange(0.1,0.1).astype(complex)]; 

实际上,我们不需要迭代。复杂的数组可以正常工作:

In [60]: x = np.arange(0.1,0.1).astype(complex)                                                
In [61]: binet(x)                                                                                    
Out[61]: 
array([0.06391735-1.31703889e-01j,0.16378803-2.38746028e-01j,0.28913834-3.13167258e-01j,0.42813892-3.50853867e-01j,0.56886448-3.51577584e-01j,0.70044744-3.18660871e-01j,0.81402504-2.58333837e-01j,0.9034083 -1.78872498e-01j,...
       4.32034432-3.76903988e-02j,4.54051382-2.60971457e-02j,4.76690299-1.30754885e-02j,5.        +0.00000000e+00j])