当我尝试在 python 中制作 3D 图形时输入错误

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.cosmath.sqrt 期望获得一个标量值,但却传递了一个 array type that they cannot handle properly which results in your type error. Essentially Python's built in math functions don't know how to deal with numpy arrays, so to fix this you need to use the mathematical functions that numpy provides to work on these data types: numpy.cos and numpy.sqrt

这将为您提供所需的矢量化。