简体   繁体   English

创建一个带有 if 语句的函数

[英]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.我想用if语句编写一个诸如f(x)的函数,并使该函数可从另一个文件访问,或多或少就好像它是一个sin(x)函数。 Moreover, I'd like to plot this function for a range of x values, but I keep getting an error.此外,我想为一系列x值绘制此函数,但我不断收到错误消息。 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;表达式es < 0.002产生一个布尔数组; 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:如果单个值小于0.002则为True ,否则为False

>>> 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:您不能在if测试中使用该数组,因为您无法明确说明这是对还是错:

>>> 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.any()你会得到True因为数组中至少有一个True值; a.all() would give you False because not all values are true: a.all()会给你False因为不是所有的值都是真的:

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

Pick the one that fits your needs, and use that in the if statement:选择一个适合您的需求,并在if语句中使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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