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

如何让Matplotlib动态生成的二次函数图像标题显示为最简形式?

解决Matplotlib动态生成最简二次多项式标题的问题

直接拼接变量生成LaTeX标题会保留冗余的系数(如1、0)和错误的符号格式,你需要编写一个辅助函数来处理每个项的系数,生成符合数学规范的最简表达式。

实现代码

import matplotlib.pyplot as plt

def get_quadratic_title(a, b, c):
    terms = []
    # 处理二次项
    if a != 0:
        if abs(a) == 1:
            term = "x^2" if a > 0 else "-x^2"
        else:
            term = f"{a}x^2"
        terms.append(term)
    # 处理一次项
    if b != 0:
        sign = "+" if b > 0 else "-"
        coeff = abs(b)
        term = f"{sign}x" if coeff == 1 else f"{sign}{coeff}x"
        terms.append(term)
    # 处理常数项
    if c != 0:
        if not terms:
            term = f"{c}"
        else:
            sign = "+" if c > 0 else "-"
            term = f"{sign}{abs(c)}"
        terms.append(term)
    # 处理全零情况
    if not terms:
        return "$0$"
    # 拼接并移除开头多余的+号
    full_expr = "".join(terms).lstrip("+")
    return f"${full_expr}$"

# 测试示例
a, b, c = 1, 0, -1
plt.plot([-2, 2], [x**2 -1 for x in [-2, 2]])
plt.title(get_quadratic_title(a, b, c))
plt.show()

关键处理逻辑

  • 二次项:系数为±1时省略数字,仅保留符号和x^2;系数为0时不显示该项
  • 一次项:系数为±1时省略数字,根据正负号添加+x或-x;系数为0时不显示该项
  • 常数项:若前面无其他项,直接显示数字;否则根据正负号添加+c或-|c|
  • 符号优化:自动移除表达式开头多余的+号,避免出现+x^2这类不规范写法

测试用例验证

  • 输入a=1, b=0, c=-1 → 输出$x^2-1$
  • 输入a=-2, b=3, c=0 → 输出$-2x^2+3x$
  • 输入a=0, b=-1, c=5 → 输出$-x+5$
  • 输入a=0, b=0, c=7 → 输出$7$

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 23:00:08