Mik*_*ing 1 python numpy matplotlib
我知道其他人看到类似的错误(TypeError:图像数据无法转换为浮点数,TypeError:图像数据无法使用matplotlib转换为浮点数,类型错误:图像数据无法转换为浮点数)但我看不到任何错误解决那里帮助我.
我正在尝试使用浮点数据填充一个numpy-array,并使用imshow填充它.Y方向(几乎)是Hermite多项式和高斯包络的数据,而X方向只是高斯包络.
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
####First we set Ne
Ne=25
###Set up a mesh with size sqrt(Ne) X sqrt(Ne)
sqrtNe=int(np.sqrt(Ne))
Ky=np.array(range(-sqrtNe,sqrtNe+1),dtype=float)
Kx=np.array(range(-sqrtNe,sqrtNe+1),dtype=float)
[KXmesh,KYmesh]=np.meshgrid(Kx,Ky,indexing='ij')
##X-direction is gussian envelope
AxMesh=np.exp(-(np.pi*KXmesh**2)/(4.0*Ne))
Nerror=21 ###This is where the error shows up
for n in range(Nerror,Ne):
##Y-direction is a polynomial of degree n ....
AyMesh=0.0
for i in range(n/2+1):
AyMesh+=(-1)**i*(np.sqrt(2*np.pi)*2*KYmesh)**(n-2*i)/(np.math.factorial(n-2*i)*np.math.factorial(i))
### .... times a gaussian envelope
AyMesh=AyMesh*np.exp(-np.pi*KYmesh**2)
AyMesh=AyMesh/np.max(np.abs(AyMesh))
WeightMesh=AyMesh*AxMesh
print("n:",n)
plt.figure()
####Error occurs here #####
plt.imshow(WeightMesh,interpolation='nearest')
plt.show(block=False)
Run Code Online (Sandbox Code Playgroud)
当代码到达impow然后我得到以下错误消息
Traceback (most recent call last):
File "FDOccupation_mimimal.py", line 30, in <module>
plt.imshow(WeightMesh,interpolation='nearest')
File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 3022, in imshow
**kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/__init__.py", line 1814, in inner
return func(ax, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib/axes/_axes.py", line 4947, in imshow
im.set_data(X)
File "/usr/lib/python2.7/dist-packages/matplotlib/image.py", line 449, in set_data
raise TypeError("Image data can not convert to float")
TypeError: Image data can not convert to float
Run Code Online (Sandbox Code Playgroud)
如果我替换代码
AyMesh=0.0
for i in range(n/2+1):
AyMesh+=(-1)**i*(np.sqrt(2*np.pi)*2*KYmesh)**(n-2*i)/(np.math.factorial(n-2*i)*np.math.factorial(i))
### .... times a gaussian envelope
AyMesh=AyMesh*np.exp(-np.pi*KYmesh**2)
AyMesh=AyMesh/np.max(np.abs(AyMesh))
Run Code Online (Sandbox Code Playgroud)
简单地说
AyMesh=KYmesh**n*np.exp(-np.pi*KYmesh**2)
AyMesh=AyMesh/np.max(np.abs(AyMesh))
Run Code Online (Sandbox Code Playgroud)
问题消失了!?有谁知道这里发生了什么?
对于较大的值,np.math.factorial返回a long而不是a int.long值为dtype的数组object为无法使用NumPy类型存储的数组.您可以重新转换最终结果
WeightMesh=np.array(AyMesh*AxMesh, dtype=float)
Run Code Online (Sandbox Code Playgroud)
有一个合适的浮点数组.