Jordan Morris
Jordan Morris

Reputation: 1

Error in for loop using a function within a function

I am defining a function to create a polynomial from data, defining another function to use this polynomial in an equation and then using a for loop for it to run until the value that is being calculated is equal or less than 0. When running the for loop, it gives the following error for when the loop is supposed to end - ' The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() '

def poly(Hi):
return np.poly1d(np.polyfit(xs, ys, deg=5))

def hip1(Hi,g,e,d,dt):
return Hi -((np.pi*d**2)*np.sqrt(2*g*(Hi + e))*dt) / (4*poly(Hi))

H = [6]
t = [0]
dt = 1
d = 0.25
e = 1
g = 9.81

for i in range(1000000):
t.append((i+1)*dt)
H.append(hip1(H[i],g,e,d,dt))
if H[i+1] < 0: break

------------------------------------------------------------------------
ValueError                                Traceback (most recent call 
last)
<ipython-input-11-a17bdee03e19> in <module>
  2     t.append((i+1)*dt)
  3     H.append(hip1(H[i],g,e,d,dt))
----> 4     if H[i+1] < 0: break

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

Upvotes: 0

Views: 41

Answers (1)

damdamo
damdamo

Reputation: 353

I tried to run your code to understand the problem.

I ran this code:

for i in range(1000000):
    t.append((i+1)*dt)
    H.append(hip1(H[i],g,e,d,dt))
    print(H)
    print(i)
    if H[i+1] < 0:
        break

I've tested to print H and i. So, the loop crash at the first iteration and print:

H = [6, array([2.54840628, 2.54840628, 2.54840628, 2.54840628, 2.54840628, 2.54840628])]

Hence, you can't access to the H[i+1] value seeing that it's an array. Your function hip1 return another array and not a single value.

EDIT:

New version of your code:

H = [6]
t = [0]
dt = 1
d = 0.25
e = 1
g = 9.81
xs = [6, 5, 4, 3, 2, 1, 0]
ys = [11700, 9700, 6700, 4500, 3200, 1800, 0]


for i in range(10000):
    t.append((i+1)*dt)
    H.append(np.mean(hip1(H[i],g,e,d,dt)))
    if H[i+1] < 0:
        break

print(H)

For the last problem, I've just used the mean of the array return by hip1. It seems that the value of the array was closed, so it was a solution to have a single value. Maybe it's wrong in your context, but the idea is to have an only value and not an array.

Now, you can easily run your program and test your values.

Upvotes: 2

Related Questions