[英]how can I plot my own function in python?
我在 python 中创建了一个 function 并且我喜欢 plot 它在现场 (0:100)。 所以我定义了一个向量x
,但是当我想为每个x
计算y
时,python 会返回这个错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
谁能帮我?
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)
因为您的 function efficieny
只能应用于单个值,而不是数组x
。
尝试将 y 设置为:
y=[efficiency (i) for i in x]
#print (y)
plot.plot(x, y)
您可以矢量化您的 function。 目前 function 仅适用于标量输入。 这就是为什么您的 function 对于 numpy 阵列失败的原因,因为if (teta >= 3.025):
对于 arrays。
您可以使用 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.