Trying To Plot A Defined Function
I have a problem. I'm trying to plot a function for different values of d. I have defined d as: d = np.arange(0.0, 100.0, 0.01) But I still get the same error: TypeError: only l
Solution 1:
You have to vectorize your function teo_function
to work with an array:
import numpy as np
import matplotlib.pyplot as plt
import math
defteo_function(d):
return2*math.pi*math.sqrt(((1**2)/(12+d**2))/9.81*d)
vecfunc = np.vectorize(teo_function)
d = np.arange(0.0, 100.0, 0.01)
T = vecfunc(d)
plt.plot (d, T, 'bo', d, T, 'k')
plt.show()
Solution 2:
the function teo_function
uses math.sqrt
which works on scalars, not on arrays. If you ever use numpy arrays, use the math operations which are included in numpy
, eg. numpy.sqrt
. Numpy has equivalent to all functions i know in the math.module
optimized for use in numpy arrays.
Numpy's functions will also work on scalars, lists, tuples and more types.
eg:
def teo_function(d):
return2*np.pi*np.sqrt(((1**2)/(12+d**2))/9.81*d)
Solution 3:
Another way. If you want your function to return a list
def teo_function(ds):
return [2*math.pi*math.sqrt(((1**2)/(12+d**2))/9.81*d) for d in ds]
Post a Comment for "Trying To Plot A Defined Function"