2

I'm developing (in order to learn python) a simple hierarchy of classes with the aims to solve differential equation (ordinary or system of) in the case of system the dependent variable have to became an numpy.array in order to use each index (like y[0], y[1] ) to represent a 2 different variable that in mathematics are dy1/dt = f(y1) dy2/dt=f(y2)

using this solver when you deal with ordinary equations the array y have shape = 1, and the size of the N elements.

Now given all this boring theory I used to define the several equation (system) or the single equations by means of lambda function like in this case :

func01 = lambda t,u : 1 - np.exp(-0.5*(t-5))

this represent the answer of a single step , indeed the analytical solution also given by lambda is the follow:

anal01 = lambda x,y : 0 if x < 5 else 1

but now I got a problem (is the first time that I use lambda with if conditions) the interpreter tell me this :

  anal01 = lambda x,y : 0 if x < 5 else 1
    ValueError: The truth value of an array with more than one element is ambiguous.  
    Use a.any() or a.all()

Now I'm already came across this problem ... when for example inside a solver the comparison of single value and y vector comes up .. and I've done like the compiler tell me to do .. and use the form error.all() = y_new- y_old (example)

so finally .. the question is ... how to comes up in this case ???

edit there is no variable a in my code ...

2
  • 1
    It is hard to tell how you are using the functions anal01 and func01. could you provide some context as to where the error happens? Commented Jul 16, 2018 at 17:35
  • It looks like there is a variable a that is an array, and you are passing it to anal01 as x. The error is telling you that a truth value cannot be deduced from the numpy array because you haven't specified whether the logic should be AND (a.all()) or OR (`a.any()') Commented Jul 16, 2018 at 17:38

1 Answer 1

1

To know why you get this error, see ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().


In your precise situation, why not do

>>> np.where(x < 5, 0, 1)

Example

>>> x = np.arange(10)
>>> x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.where(x < 5, 0, 1)
array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])

Using a lambda function

>>> anal01 = lambda x,y : np.where(x < 5, 0, 1)
>>> anal01(x, None)
array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])


The variable named a (that you don't have in your code) is simply used to illustrate the way you should deal with your array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.