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

如何在Python中求解指定方程的y并绘制y-x关系图(x∈[0,1])

在Python中求解方程并绘制y-x关系图

对应你在Mathematica中的一行实现,Python可以通过**sympy(符号计算)和matplotlib(绘图)**完成,步骤如下:

1. 安装依赖库

如果还没装需要的库,先执行:

pip install sympy matplotlib numpy

2. 完整代码实现

import sympy as sp
import matplotlib.pyplot as plt
import numpy as np

# 定义符号变量
x, y = sp.symbols('x y')

# 构造方程(对应Mathematica中的等式)
equation = sp.Eq(10 * x**2 - 7 * x + 3, 2 * y + y**2)

# 求解y(对应Mathematica的Solve)
y_solutions = sp.solve(equation, y)

# 将符号解转换为可计算数值的函数(对应Mathematica的y /. Solve)
y1 = sp.lambdify(x, y_solutions[0], 'numpy')
y2 = sp.lambdify(x, y_solutions[1], 'numpy')

# 生成x的取值区间(0到1,100个采样点)
x_values = np.linspace(0, 1, 100)

# 计算对应的y值
y1_values = y1(x_values)
y2_values = y2(x_values)

# 绘图(对应Mathematica的Plot)
plt.plot(x_values, y1_values, label='y₁')
plt.plot(x_values, y2_values, label='y₂')
plt.xlabel('x')
plt.ylabel('y')
plt.title('y与x的关系(0 ≤ x ≤ 1)')
plt.legend()
plt.grid(True)
plt.show()

关键步骤说明

  • 符号求解:用sympy.solve解二次方程,得到两个解析解,对应Mathematica的Solve函数。
  • 转数值函数:sp.lambdify把sympy的符号表达式转换成numpy兼容的函数,方便批量计算x对应的y值,等价于Mathematica中y /. Solve的替换操作。
  • 绘图:用matplotlib的plot函数分别绘制两个解的曲线,设置标签、坐标轴和网格,完成可视化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:10:32