user8953650
user8953650

Reputation: 1020

python difficults to set a lambda function

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 ...

Upvotes: 2

Views: 184

Answers (1)

keepAlive
keepAlive

Reputation: 6665

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.

Upvotes: 1

Related Questions