Type Error when I try to make a 3D graph in python
Question: I know how to make 3D-graph in Python but for this one I have an error I've
never seen. 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... ???)

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


Answer: `math.cos` and `math.sqrt` expect to get a scalar value but instead were
passed an [array type](http://docs.scipy.org/doc/numpy/reference/arrays.html)
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](http://docs.scipy.org/doc/numpy/reference/generated/numpy.cos.html#numpy.cos)
and
[numpy.sqrt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.sqrt.html#numpy.sqrt)

This will then give you the vectorization you need.

