Python二次函数绘图与根求解问题求助(含代码)
Python绘图与二次方程正根求解
任务要求
- 绘制函数
y = x**2 + x - 11在x∈[-100,100]、步长0.01的图像; - 通过迭代调整坐标轴范围找到函数的正根(满足
x**2 + x -11 = 0且x>0); - 设置x轴范围使根位于中心且总宽度为0.30,y轴范围在
[-1,1]之间,从图中读取正根值并保留两位小数赋值给x2。
现有代码与尝试
初始代码:
import numpy as np import matplotlib.pyplot as plt x = np.arange(-100,100,0.01) y = x**2 + x - 11 # Graphics commands here x2 = plt.figure(figsize=(8,5)) plt.plot(x, y) plt.xlim(-25,25) plt.ylim(-100,600) plt.grid(True) plt.title("y = x**2 + x - 11") plt.show()
尝试的代码片段:
x1 = (-1 + np.sqrt(1**2 - (4 * 1 *-11)))/(2*1) x2 = (-1 - np.sqrt(1**2 - (4 * 1 *-11)))/(2*1) plt.plot([x1, x2], [0, 0], linestyle = "None", marker = "x")
疑问解答
1. 如何找到函数的正根?
- 公式法:你写的求根公式是正确的。二次方程
ax²+bx+c=0的根为x = [-b ± √(b²-4ac)]/(2a),代入a=1, b=1, c=-11,计算得正根为x1 = (-1 + √45)/2 ≈ 2.85,另一个根x2是负数,无需关注。 - 迭代缩范围法:先绘制全范围图像,然后逐步缩小x轴范围(比如从
[-100,100]→[-10,10]→[0,5]→[2,3]),直到清晰看到函数与y=0的交点,即为正根位置。
2. 如何按要求设置x轴范围?
要求正根位于x轴中心,总宽度0.30,意味着根到左右边界的距离各为0.15。设正根为x_root,则x轴范围为[x_root - 0.15, x_root + 0.15],用代码plt.xlim(x_root - 0.15, x_root + 0.15)实现即可。
3. 如何从图中读取正根的值?
当把x轴缩到根附近(比如[2.7, 3.0])、y轴设为[-1,1]后,观察函数与y=0的交点位置,结合x轴刻度读取数值,保留两位小数后赋值给x2。也可以直接用求根公式计算结果四舍五入,和读图结果一致。
完整代码
import numpy as np import matplotlib.pyplot as plt # 生成x和y数据 x = np.arange(-100, 100, 0.01) y = x**2 + x - 11 # 计算正根并保留两位小数赋值给x2 x_root = (-1 + np.sqrt(1**2 - 4*1*(-11))) / (2*1) x2 = round(x_root, 2) # 绘图 plt.figure(figsize=(8,5)) plt.plot(x, y) # 标记正根位置 plt.plot(x_root, 0, marker='x', color='red', label=f'正根 x≈{x2}') # 设置x轴范围:根居中,总宽度0.30 plt.xlim(x_root - 0.15, x_root + 0.15) # 设置y轴范围 plt.ylim(-1, 1) plt.grid(True) plt.title("y = x**2 + x - 11") plt.legend() plt.show() # 输出结果 print(f"正根值x2 = {x2}")
内容的提问来源于stack exchange,提问作者Ramon
相关产品推荐
相关产品推荐

