[英]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.