我正在尝试用python表达以下函数,我想绘制它们
import matplotlib.pyplot as plt
import numpy as np
ss = np.linspace(300, 1000, 15)
def PT3000(ss):
if ss < 318.842719019854:
PT3 = 4.602 + 37440.0/ss
else :
PT3 =-0.3 + 3600.0/ss
return PT3
def PT2000(ss):
if ss < 318.842719019854:
PT2 = 4.602 + 37440.0/ss
elif ss > 945.33959:
PT2 =-0.3 + 3600.0/ss
else:
PT2 = 6.87109574235995e-6*ss**0.5*(-1 + 96000.0/ss) + 62.144
return PT2
fig= plt.figure()
plt.plot(ss,PT2000(ss))
plt.plot(ss,PT3000(ss))
plt.title('Productietijd [24x12]')
plt.xlabel('Verstijverafstand [mm]')
plt.ylabel('Productijd van een paneel [uur]')
plt.grid(visible=True)
plt.legend()
plt.show()
我遇到了一个错误,但我不知道该怎么做
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
应将PT2000
和PT3000
应用于ss
的每个元素。然而,Python一次传递整个数组ss
,并让NumPy处理它。
NumPy数组的比较返回一个数组,所以像ss < 318.842719019854
这样的代码结果是一个布尔值数组。因此,if
语句变成如下所示:
if np.array([False, True, False, ...]):
# do stuff
...
"包含多个元素的数组的真值是不确定的,因为数组可以同时包含True
值和False
值。
True
。这不是您在这里需要的,因为像PT2000
和PT3000
这样的分段函数作用于单个数字,而不是整个数组。
你可以使用numpy.vectorize
来应用你的函数:
PT3000_vectorized = np.vectorize(PT3000)
plt.plot(ss, PT2000_vectorized(ss))
这将迭代ss
,并将其单个元素传递给函数,因此比较只涉及float
s。
import matplotlib.legend as legend
import matplotlib.pyplot as plt
import numpy as np
ss = np.linspace(300, 1000, 15)
def PT3000(ss):
if np.all(ss < 318.842719019854):
PT3 = 4.602 + 37440.0/ss
else :
PT3 =-0.3 + 3600.0/ss
return PT3
def PT2000(ss):
if np.all(ss < 318.842719019854) :
PT2 = 4.602 + 37440.0/ss
elif np.all(ss > 945.33959):
PT2 =-0.3 + 3600.0/ss
else:
PT2 = 6.87109574235995e-6*ss**0.5*(-1 + 96000.0/ss) + 62.144
return PT2
fig= plt.figure()
plt.plot(ss,PT2000(ss), label='PT2000')
plt.plot(ss,PT3000(ss), label='PT3000')
plt.title('Productietijd [24x12]')
plt.xlabel('Verstijverafstand [mm]')
plt.ylabel('Productijd van een paneel [uur]')
plt.grid(visible=True)
plt.legend(loc='upper left')
plt.show()