You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SymPy中化简复合不等式?以4 < x - 8 < 10为例

用SymPy处理复合不等式的方法

SymPy其实支持处理复合不等式,核心是用**逻辑与(&/And)和逻辑或(|/Or)**来组合子不等式,再通过reduce_inequalities()或solve()求解,以下是具体用法:

1. 逻辑与(同时满足多个不等式)

用&符号或And()函数组合子不等式,传入reduce_inequalities()求解:

from sympy import symbols, reduce_inequalities, And

x = symbols('x')
# 两种写法等价:用&或And()
compound_ineq_and = (x > 2) & (x < 5)
# compound_ineq_and = And(x > 2, x < 5)
result = reduce_inequalities(compound_ineq_and, x)
print(result)  # 输出:2 < x ∧ x < 5

2. 逻辑或(满足任意一个不等式)

用|符号或Or()函数组合子不等式:

from sympy import symbols, reduce_inequalities, Or

x = symbols('x')
compound_ineq_or = (x < 1) | (x > 3)
# compound_ineq_or = Or(x < 1, x > 3)
result = reduce_inequalities(compound_ineq_or, x)
print(result)  # 输出:x < 1 ∨ x > 3

注意事项

  • 必须使用SymPy的逻辑运算符&/|,而非Python原生的and/or——后者会将表达式转换为布尔值,导致求解错误。
  • 建议给每个子不等式加上括号,避免运算符优先级引发的歧义。
  • 嵌套复合不等式也可处理,比如(x > 0 & x < 2) | (x > 4 & x < 6),直接传入reduce_inequalities()即可。

内容的提问来源于stack exchange,提问作者Kevin Schnaubelt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:25:24