I create a function in python and I like to plot it on set (0:100). So I have defined an vector x
, but when I want to calculate y
for each x
, the python returns me this error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Can anyone help me?
g = 9.81
Qave = 0.05
def efficiency(h):
Qn = 3e-5 *np.sqrt(2*g*h)
NN = np.ceil(Qave/Qn)
teta = 0.9 * np.sqrt(2*g*h)
if (teta>=3.025):
Kl = 2e-5
else:
Kl = 2*np.sqrt(1e-9/np.pi*teta)
inverse_efficiency = np.exp(-Kl*1.2e4*teta)
return(inverse_efficiency)
# plot data
x = np.arange(0.01, 100, 0.01)
y=efficiency(x)
plot.plot(time, amplitude)
Because your function efficieny
can only be applied on a single value, not an array x
.
Try to set y as:
y=[efficiency (i) for i in x]
#print (y)
plot.plot(x, y)
You can vectorize your function. At the moment the function only works for scalar inputs. That is why your function fails for a numpy array, because the if (teta >= 3.025):
for arrays.
You can fix your code by using numpys vectorization.
import numpy as np
import matplotlib.pyplot as plt
g = 9.81
Qave = 0.05
def efficiency(h):
Qn = 3e-5 * np.sqrt(2 * g * h)
NN = np.ceil(Qave / Qn)
teta = 0.9 * np.sqrt(2 * g * h)
if teta >= 3.025:
Kl = 2e-5
else:
Kl = 2 * np.sqrt(1e-9 / np.pi * teta)
inverse_efficiency = np.exp(-Kl * 1.2e4 * teta)
return (inverse_efficiency)
efficiency_vector = np.vectorize(efficiency)
# plot data
h = np.arange(0.01, 100, 0.01)
efficiency = efficiency_vector(h)
plt.plot(h, efficiency)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.