简体   繁体   English

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

[英]Type Error when I try to make a 3D graph in python

I know how to make 3D-graph in Python but for this one I have an error I've never seen.我知道如何在 Python 中制作 3D 图形,但是对于这个,我有一个我从未见过的错误。 I want to have the graph of :我想要图:

$$f(x,y)=\\frac{8\\cos(\\sqrt{x^2+y^2}}{\\sqrt{1+x^2+y^2}}$$ (LaTeX doesn't work here... ???) $$f(x,y)=\\frac{8\\cos(\\sqrt{x^2+y^2}}{\\sqrt{1+x^2+y^2}}$$ (LaTeX 没有在这里工作......?)

My code :我的代码:

    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()

The error :错误 :

 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

Can you explain me what I have to do?你能解释一下我必须做什么吗?

Thank you in advance先感谢您

math.cos and math.sqrt expect to get a scalar value but instead were passed an array type that they cannot handle properly which results in your type error. math.cosmath.sqrt期望获得一个标量值,但却传递了一个他们无法正确处理的数组类型,这会导致您的类型错误。 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本质上,Python 的内置数学函数不知道如何处理 numpy 数组,因此要解决此问题,您需要使用 numpy 提供的数学函数来处理这些数据类型: numpy.cosnumpy.sqrt

This will then give you the vectorization you need.这将为您提供所需的矢量化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM