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

Question:

My question is related to the answer to my previous question.

the difference between the code in the previous solutions and the current code on this question is as follows: on my code, I have to set the function "myfunc" returns two different results,
if t==0: return(10) else: return np.sqrt(r**2 - t**2) instead of just one return which is: return np.sqrt(r**2 - t**2) .

know if you run the file it will raise a ValueErrore,

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

can someone explain to me how to solve this, without changing the function to return one result because I need to keep it returning two results, this is just an example of the problem I have, the program I am writing is much different from this one.

thank you so much

from matplotlib import pyplot as plt
import numpy as np

# create the function (which you may not have access to)
def myfunc(t, r=1.0):
    if t==0:
        return (10)
    else:
        return np.sqrt(r**2 - t**2)

# generate some points at which the function has been evaluate
t = np.linspace(0, 1, 100)  # 100 points linearly spaced between 0 and 1
y = myfunc(t)  # the function evaluated at the points t

# assuming we just have t and y (and not myfunc), interpolate the value of
# the function at some point t1
t1 = 0.68354844
y1 = np.interp(t1, t, y)

# use piecewise to get a function which is constant below t1 and follows the
# original function above t1 (potentially evaluated at different points in t)
tnew = np.linspace(0, 1, 150)  # new (more highly sampled) points at which to evaluate the function

condlist = [tnew <= t1, tnew > t1]  # list of piecewise conditions
funclist = [y1, np.interp]  # use constant y1 for first condition and interp for second condition

# evaluate the piecewise function at tnew
yvals = np.piecewise(tnew, condlist, funclist, t, y)

# plot the original function and the new version with the constant section
fig, ax = plt.subplots()
ax.plot(t, y, label="Original function")
ax.plot(tnew, yvals, ls="--", label="Piecewise function")
ax.legend()

fig.show() 

I am still a beginner to programming in general so please, it will be really helpful if you can write an answer that can be easy for me to understand, I really appreciate it.

Asked By: mizzo

||

Answers:

What do you mean by t==0? t is a numpy array (you define it as a linspace). If you mean one value from the array, then you need to iterate over it or use apply method

y = np.array([myfunc(x) for x in t])

Answered By: Leonid Astrin

You just have to replace the t == 0 with t.any() == 0
Like below the code:

if t == 0:
if t.any() == 0:

As the t is an numpy array you have to check all the values inside the numpy array variable t

Answered By: Manvi

There are a few different options, so I’ll try to cover each. I think you are suggesting that if you pass t as a single numeric value and that value is 0, then the function should just return single value of 10, but you still want it to also work when t is an array. In that case you could do:

def myfunc(t, r=1.0):
    # check whether t is just a number (either an integer or floating point number)
    if isinstance(t, (int, float)):
        # check if t is zero
        if t == 0:
            return 10

    return np.sqrt(r**2 - t**2)

If, on the other hand you expect t to always be an array, and want myfunc to just return a single value of 10 if the array of t values contains 0, then you could do:

def myfunc(t, r=1.0):
    # check whether t contains a zero
    if np.any(t == 0):
        return 10

    return np.sqrt(r**2 - t**2)

Finally, if you want myfunc to take in an array of t values and always output an array of values the same size as t, but with indexes where t is zero set to contain the value 10, the you could do:

def myfunc(t, r=1.0):
    f = np.sqrt(r**2 - t**2)  # evaluate the function at all value

    # set values where t is zero to 10
    f[t == 0.0] = 10

    return f

I hope that covers all your potential options.

Answered By: Matt Pitkin