Wallika
Wallika

Reputation: 49

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() for plotting

x = [0,20,40,60,80,100]

y= [26.0,48.6,61.6,71.2,74.8,75.2]


then I define the function 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)

and, It works and it returns me a true output which is 66.4, but I planned to plot the sequence number as a parameter of x_to_find, so I did prepare x and function of x as a parameter

t = np.arange(0, 100, 0.001)

Linear_Int(x,y,t)

It threw me an error "`The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()`" I wish I could get a function like this, but it doesn't work like this one which returns me a ton of value of a function of t

t = np.arange(x[0], x[-1], 0.001)
def g(x):
  return x**2
g(t)

Why It doesn't work like the above function?

Upvotes: 0

Views: 301

Answers (1)

Epsi95
Epsi95

Reputation: 9047

x = [0,20,40,60,80,100]

y= [26.0,48.6,61.6,71.2,74.8,75.2]


Iterative solution

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

Vectorized solution

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

Upvotes: 1

Related Questions