0

In this program, I have encountered the error:

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

Given that the value of alpha in each iteration is only one number, why this error occurs.

    while rho>1e-3:
        print(alpha)
        if alpha>-90 and alpha<=90:
            rho_dot,alpha_dot,beta_dot = [-k_rho*rho*math.cos(alpha),
                                  k_rho*math.sin(alpha)-k_alpha*alpha-k_beta*beta,-k_rho*math.sin(alpha)]
            
        if np.union1d((alpha>-180 and alpha<=-90),(alpha>90 and alpha<=180)):
            rho_dot,alpha_dot,beta_dot = [k_rho*rho*math.cos(alpha),-k_rho*math.sin(alpha)+k_alpha*alpha+k_beta*beta,k_rho*math.sin(alpha)]
            

2 Answers2

0

Whilst alpha is always one number, np.union1d((alpha>-180 and alpha<=-90),(alpha>90 and alpha<=180)) is a list which can have more than one element. You should change that line to be:

if any(i for i in np.union1d((alpha>-180 and alpha<=-90),(alpha>90 and alpha<=180))):

or to:

if all(i for i in np.union1d((alpha>-180 and alpha<=-90),(alpha>90 and alpha<=180))):

Depending on whether you want any elements in np.union1d((alpha>-180 and alpha<=-90),(alpha>90 and alpha<=180)) to be true or all of them for the condition to be satisfied.

Also, I think you need to add an:

else:
    break

clause after that as otherwise you become stuck in an infinite loop.

Nin17
  • 2,821
  • 2
  • 4
  • 14
0

You can fix this error by changing the offending line (the one with union1d) to this:

if np.union1d((alpha>-180 and alpha<=-90),(alpha>90 and alpha<=180)).any():

Internally, the any() method will iterate through the elements of the array result from union1d (even if there is only one element) to test whether alpha is either between -180 and -90 or between 90 and 180 (or, in the general case, both, though that would be arithmetically possible in your particular case).

For the motivation of numpy developers in deciding that your original usage should generate an error, please see this answser: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

constantstranger
  • 9,176
  • 2
  • 5
  • 19