[英]Type Error when I try to make a 3D graph in python
我知道如何在 Python 中制作 3D 圖形,但是對於這個,我有一個我從未見過的錯誤。 我想要圖:
$$f(x,y)=\\frac{8\\cos(\\sqrt{x^2+y^2}}{\\sqrt{1+x^2+y^2}}$$ (LaTeX 沒有在這里工作......?)
我的代碼:
import math
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
ax = Axes3D(plt.figure())
def f(x,y):
return (8*math.cos(math.sqrt(x**2+y**2)))/(math.sqrt(1+x**2+y**2))
X = np.arange(-1,1,0.1)
Y = np.arange(-1,1,0.1)
X,Y=np.meshgrid(X,Y)
Z=f(X,Y)
ax.plot_surface(X,Y,Z)
plt.show()
錯誤 :
runfile('C:/Users/Asus/Desktop/Informatiques/nodgim.py', wdir=r'C:/Users/Asus/Desktop/Informatiques')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Asus\Desktop\WinPython\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 680, in runfile
execfile(filename, namespace)
File "C:\Users\Asus\Desktop\WinPython\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/Asus/Desktop/Informatiques/nodgim.py", line 22, in <module>
Z=f(X,Y)
File "C:/Users/Asus/Desktop/Informatiques/nodgim.py", line 16, in f
return (8*math.cos(math.sqrt(x**2+y**2)))/(math.sqrt(1+x**2+y**2))
TypeError: only length-1 arrays can be converted to Python scalars
你能解釋一下我必須做什么嗎?
先感謝您
math.cos
和math.sqrt
期望獲得一個標量值,但卻傳遞了一個他們無法正確處理的數組類型,這會導致您的類型錯誤。 本質上,Python 的內置數學函數不知道如何處理 numpy 數組,因此要解決此問題,您需要使用 numpy 提供的數學函數來處理這些數據類型: numpy.cos和numpy.sqrt
這將為您提供所需的矢量化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.