tes183
tes183

Reputation: 1

Python ValueError abs of an array

I am new to python and have been unable to figure out how to fix this. I am trying to do an iteration for each value in the array, and return the array of final values. e is a user-input single value, while M is an array of varying length. I am trying to loop the iteration for each value of E until it closely solves Kepler's equation, M=E-e*sin(E), and then return the finished array of each E for given M.

def eccano(e, M):
   E=M
   for i in range(0,len(M)):
       while abs(E-e*sin(E)-M[i]) > 10**(-4):
           E=E-((E-e*sin(E)-M[i])/(1-e*cos(E)))
   return E

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ME.py", line 7, in eccano
    while abs(E-e*sin(E)-M[i]) > 10**(-4):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Any advice? Thanks!

Upvotes: 0

Views: 1669

Answers (3)

Benjamin
Benjamin

Reputation: 11860

This looks like an implementation of the Newton–Raphson method. I can't give specific help, because I don't know what the function is, but here's how I would code the example in the Wikipedia page:

import numpy as np

def newtons(start_value, threshold):
   x = start_value

   stop = False
   while stop == False:
      x_previous = x
      # x -= function / first derivative of function
      x -= (np.cos(x) - x**3 )/ (-np.sin(x) - 3 * x**2)

      if np.abs(x - x_previous) < threshold:
         stop = True

   return x


print newtons(0.5, 0.0001)

Let us know if this is what you are trying to do, what e and M are, and what the specific function is.

Upvotes: 0

user1091831
user1091831

Reputation: 1

Abs returns the type it is given, so you have to either select E[i], use an operation such as sum, or just have for i in E.
For example:

abs(np.array([-1, 2, -4])) = array([1, 2, 4])

Assuming you want the 2-norm of abs(E-e*sin(E)-M[i]) to be greater than 10^-4, you'd write:

np.linalg.norm(abs(E-e*sin(E)-M[i]),2) > 10**(-4)

If you are looking for something else in the loop conditional add a little more info. Right now it's not really possible to infer what you want.

Upvotes: 0

Free Monica Cellio
Free Monica Cellio

Reputation: 2290

Not sure what you're actually trying to do, but the problem is this:

while abs(E-e*sin(E)-M[i]) > 10**(-4):

All of those operations in the abs() work elementwise in numpy arrays, so you're doing some things that end with an array, taking the absolute value of every element in that array, then comparing to 10**(-4) and ending up with an array of booleans. It's complaining that it can't evaluate that as "True" or "False" because it's an array that probably contains both True and False values.

Upvotes: 1

Related Questions