包含多个元素的数组的真值是二义性的.使用a.a any()或a.a all()进行绘图


x = [0,20,40,60,80,100]
y= [26.0,48.6,61.6,71.2,74.8,75.2]

然后定义函数Linear_Int

def Linear_Int(x,y,x_to_find):
for index, e in enumerate(x):

if e > x_to_find:
y = y[index-1] + ((y[index]-y[index-1])/(x[index]-x[index-1])* (x_to_find - x[index-1]))
return y

print("Given x value is out of range")
Linear_Int(x,y,50)

和,它工作,它返回给我一个真实的输出,它是66.4,但我计划绘制序列号作为x_to_find的参数,所以我准备了x和x的函数作为参数

t = np.arange(0, 100, 0.001)
Linear_Int(x,y,t)

它给了我一个错误"`The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()`"我希望我能得到一个这样的函数,但它不像这个这样工作它返回给我一个t

的函数的大量值
t = np.arange(x[0], x[-1], 0.001)
def g(x):
return x**2
g(t)

为什么它不像上面的函数那样工作?

x = [0,20,40,60,80,100]
y= [26.0,48.6,61.6,71.2,74.8,75.2]

迭代解

def Linear_Int(x,y,x_to_find):
for index, e in enumerate(x):
if e > x_to_find:
y = y[index-1] + ((y[index]-y[index-1])/(x[index]-x[index-1])* (x_to_find - x[index-1]))
return y
print("Given x value is out of range")

t1 = time.time()
a1 = [Linear_Int(x,y,i) for i in t]
t2 = time.time()
print(t2-t1)
0.3699524402618408 seconds

矢量解

def Linear_Int_vctorized(x_,y_,x_to_find):
bb = x_ > t[:, np.newaxis]
indexes = np.argwhere(bb.cumsum(axis=1)==1)[:, 1]
out = y_[indexes-1] + ((y_[indexes] - y_[indexes-1])/(x_[indexes] - x_[indexes-1]) * (t-x_[indexes-1]))
return out
x_ = np.array(x)
y_ = np.array(y)
t1 = time.time()
a2 =  Linear_Int_vctorized(x_,y_, t)
t2 = time.time()
print(t2-t1)
0.022547245025634766 seconds
all(a1 == a2)
>>> True

相关内容

  • 没有找到相关文章

最新更新