python - 如何在 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 无法通过比较来处理函数。当我尝试分段函数时,它给出了同样的错误,它还包括一个比较过程。
解决方案
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
推荐阅读
- python - 使用 for 循环进行二分搜索,在列表中搜索单词并进行比较
- botframework - 如何使用 appinsights 调用我们自己的 qnamakerservice
- javascript - 如何在从 API 获取数据时添加加载动画?香草js
- r - 分配类似于r中的括号(x <-27)技巧后如何在新行上打印变量
- php - android json 获取请求
- java - 将集合中的新元素与另一集合中的旧元素进行比较 - Java
- c# - 在不和谐的 PM 中记录回复
- scala - 如何将结果从一个源流传递到另一个源流
- kotlin - 在 Kotlin 中使用 Java 库时,是否更习惯使用 ? 或者 !!关于方法返回值?
- c++ - 为什么'for_each'不读取函数对象