Files
CalWay_Python/159-2.py
2025-06-14 11:40:57 +08:00

36 lines
1.2 KiB
Python

import math
import matplotlib.pyplot as plt
#把原函数换成题干的形式########################
def fx(x):
return math.exp(x)-math.sin(x)
# 绘制函数图像 并标记可能的零点
def DrawGraph(a, b, stepper):
x = [a + (b-a)*i*stepper for i in range(int(1/stepper+1))]
y = [fx(i) for i in x]
plt.xlim(a-abs(b-a)*0.1, b+abs(b-a)*0.1)
plt.plot(x, y)
plt.axhline(0, color='black', lw=0.5, ls='-')
plt.axvline(a, color='red', lw=0.5, ls='--')
plt.axvline(b, color='red', lw=0.5, ls='--')
plt.text(a, y[0], f'({a:.5f},{y[0]:.5f})', fontsize=8, ha='left')
plt.text(b, y[-1], f'({b:.5f},{y[-1]:.5f})', fontsize=8, ha='right')
for i in range(len(x)-1):
if y[i] * y[i+1] < 0:
print(f"可能存在零点: ({x[i]:.5f},{y[i]:.5f})和({x[i+1]:.5f},{y[i+1]:.5f})之间")
plt.plot((x[i]+x[i+1])/2, (y[i]+y[i+1])/2, 'ro', markersize=3)
plt.title("Graph of f(x)")
plt.xlabel("x")
plt.ylabel("f(x)")
plt.show()
return x, y
#把范围改成题干的形式#######################
if __name__ == "__main__":
a = -2*math.pi
b = math.pi
step = 0.00001
print(f"边界点: {a}, {b}")
print(f"步长: {step}")
x, y = DrawGraph(a, b, step)