[英]how can I plot my own function in python?
I create a function in python and I like to plot it on set (0:100).我在 python 中创建了一个 function 并且我喜欢 plot 它在现场 (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:所以我定义了一个向量
x
,但是当我想为每个x
计算y
时,python 会返回这个错误:
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
.因为您的 function
efficieny
只能应用于单个值,而不是数组x
。
Try to set y as:尝试将 y 设置为:
y=[efficiency (i) for i in x]
#print (y)
plot.plot(x, y)
You can vectorize your function.您可以矢量化您的 function。 At the moment the function only works for scalar inputs.
目前 function 仅适用于标量输入。 That is why your function fails for a numpy array, because the
if (teta >= 3.025):
for arrays.这就是为什么您的 function 对于 numpy 阵列失败的原因,因为
if (teta >= 3.025):
对于 arrays。
You can fix your code by using numpys vectorization.您可以使用 numpys 矢量化来修复您的代码。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.