时间:2015-09-07 10:23:19

标签: python function if-statement

我想用f(x)语句编写一个函数,例如if,并使该函数可以从其他文件中访问,或多或少,就好像它是sin(x)函数一样。此外,我想为一系列x值绘制此函数,但我一直收到错误。这是我的代码:

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()

这是我收到的错误消息:

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

1 个答案:

答案 0 :(得分:0)

表达式es < 0.002产生一系列布尔值;测试输入数组中的每个值,并且每个测试的结果通知输出数组;如果该单个值小于True,则为0.002,否则为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)

您无法在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()

如果您使用a.any(),则会获得True,因为数组中至少有一个True值; a.all()会向您False提供,因为所有值均为真:

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

选择符合您需求的那个,并在if声明中使用它:

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