首页 > 解决方案 > 如何在 python 中通过 sympy 集成一个 max 函数?

问题描述

我想通过 sympy 在 python 中集成一个 max 函数。但是,似乎 sympy 无法通过关系比较来处理这样的功能。

import sympy
def func(x):
    return max(x,0)
x = sympy.symbols(x)
sympy.integrate(func(x),(x,-1,1))

运行上面的代码,它会给出错误信息:

  File "<ipython-input-11-2630b8af4afe>", line 2, in func
    return max(x,0)

  File "/Applications/anaconda/lib/python3.6/site-packages/sympy/core/relational.py", line 304, in __nonzero__
    raise TypeError("cannot determine truth value of Relational")

TypeError: cannot determine truth value of Relational

似乎 sympy 无法通过比较来处理函数。当我尝试分段函数时,它给出了同样的错误,它还包括一个比较过程。

标签: pythonsympy

解决方案


SymPy uses uppercase and lowercase names to refer (often) to functions and classes. When you get a "truth value" error it means that something that could give a True or False answer didn't (like if x < 1: print('less than 1')). If x is a Symbol then x < 1 remains a Lt(x, 1) object.

In your case, the function max tried to compare x and 0 and it couldn't get True or False comparison. Use the Max object instead to see your integral evaluate:

>>> from sympy import Max
>>> from sympy.abc import x
>>> integrate(Max(x,0),(x,-1,1))
1/2

推荐阅读