0

When using optimization (e.g. brentq), the input is always an array of items. However, sometimes it is necessary to use a comparator function like >= in object function. Then, python is not able to evaluate those values.

For example:

def f(x):
    if x > 0:
        return x
    if x <= 0:
        return -x

optimize.brentq(f,-1,1)

Then we will have the error: The truth value of an array with more than one element is ambiguous.

In general, how to avoid this error?

Palinuro
  • 184
  • 1
  • 1
  • 15
wei_q
  • 1
  • 1
    Start by reading the rest of the error message. It has some suggestions of what to do. – Code-Apprentice Jul 18 '22 at 01:55
  • Search SO with the error message and start reading the Q&A's to get a feel for the issue. – wwii Jul 18 '22 at 03:17
  • Do you want the condition to be True if ALL the elements of `x` meet the condition or just ANY of them.? What is supposed to happen for `if [True,False,True]:`? – wwii Jul 18 '22 at 03:20
  • [ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()](https://stackoverflow.com/questions/10062954/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous) – wwii Jul 18 '22 at 03:23

1 Answers1

0

If f is what you actually need, use np.abs instead. If it's a dummy example, use something like this instead:

def f(x):
    return np.where(x>0, x, -x)

In general change

def f(x):
    if condition(x):
        return f1(x)
    else:
        return f2(x)

to

def f(x):
    return np.where(condition(x), f1(x), f2(x))

keeping in mind that for non trivial conditions, your implementation should still be able to handle vectors... (i.e. if x is a vector condition(x) should return a vector of the same size as x)

Julien
  • 13,986
  • 5
  • 29
  • 53