简体   繁体   中英

Create a function with an if statement inside

I want to write a function such as f(x) with an if statement and make this function accessible from another file, more or less as if it were a sin(x) function. Moreover, I'd like to plot this function for a range of x values, but I keep getting an error. Here's my code:

import numpy as np
import matplotlib.pyplot as plt

fyd=450/1.15

def f(es):
    if es < 0.002:
        return fyd*es/0.002
    else:
        return fyd;


x=np.arange(0.0000,0.01,0.0001)

plt.plot(x,f(x))
plt.show()

And this is the error message I get:

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

The expression es < 0.002 produces an array of booleans; each value in the input array is tested and the outcome of each of those tests informs the output array; True if that individual value is smaller than 0.002 , False otherwise:

>>> import numpy as np
>>> fyd=450/1.15
>>> x=np.arange(0.0000,0.01,0.0001)
>>> x < 0.002
array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False, False], dtype=bool)

You cannot use that array in an if test, because you cannot unambiguously say if this is true or false:

>>> bool(x < 0.002)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

If you used a.any() you get True because there is at least one True value in the array; a.all() would give you False because not all values are true:

>>> (x < 0.002).any()
True
>>> (x < 0.002).all()
False

Pick the one that fits your needs, and use that in the if statement:

def f(es):
    if (es < 0.002).any():  # or .all()
        return fyd*es/0.002
    else:
        return fyd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM