如何在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
相关产品推荐
相关产品推荐

