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

如何绘制带输出限制的函数?Jupyter绘图报错求助

问题与解决方案

问题背景

在Jupyter环境中已成功用SymPy绘制发动机扭矩(torque)与转速(rpm)的关系曲线,需求是将扭矩输出值限制为500。编写带if条件的函数后,单个转速值计算结果正确,但调用plot绘图时出现错误:TypeError: cannot determine truth value of Relational。

错误原因

你定义的rpm_eng是SymPy的符号变量,Python原生的if语句无法直接判断符号表达式的真假——符号表达式的比较会返回Relational对象而非布尔值,这导致plot函数无法解析逻辑判断。

解决方案

使用SymPy内置的Piecewise函数定义分段函数,替代Python的if-else逻辑,这样符号表达式能被plot正确识别处理。

修改后的代码

第1个单元格(原代码无需修改,可正常运行)

# ENGINE
from sympy import symbols, plot

rpm_eng, torq_eng = symbols('rpm_eng, torq_eng')

def eq_torq_eng(rpm_eng):
    return -8.6916*10**-14*rpm_eng**4 + 2.3789*10**-9*rpm_eng**3 - 2.8710*10**-5*rpm_eng**2 + 1.9178*10**-1*rpm_eng + 1.5105

plot(eq_torq_eng(rpm_eng), (rpm_eng, 0, 13000), \
     title="engine output : torque vs rpm", xlabel="rpm", ylabel="torque in N.m")

第2个单元格(替换为Piecewise实现的限制函数)

from sympy import Piecewise

# 先定义基础扭矩表达式,避免重复书写
torq_expr = -8.6916*10**-14*rpm_eng**4 + 2.3789*10**-9*rpm_eng**3 - 2.8710*10**-5*rpm_eng**2 + 1.9178*10**-1*rpm_eng + 1.5105

def eq_torq_limiter(rpm_eng):
    # 使用Piecewise定义分段逻辑:当表达式>500时返回500,否则返回原表达式
    return Piecewise((500, torq_expr > 500), (torq_expr, True))

plot(eq_torq_limiter(rpm_eng), (rpm_eng, 0, 13000), \
     title="engine output : torque vs rpm (limited to 500 N.m)", xlabel="rpm", ylabel="torque in N.m")

第3个单元格(验证函数正确性,无需修改)

for rpm_val in range(1000, 14000, 1000):
    print(eq_torq_limiter(rpm_val))

说明

  • Piecewise是SymPy专门用于定义分段符号函数的工具,接受多个元组参数,每个元组格式为(返回值, 条件),最后一个元组用True表示默认情况。
  • 提取torq_expr变量是为了避免重复书写冗长的表达式,提升代码可读性。

内容的提问来源于stack exchange,提问作者Damien Dambre

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 09:51:08