用牛顿迭代法求方程e⁻ˣ-x=0在x=-2附近的一个实根。python实现
时间: 2024-05-24 22:13:03 浏览: 152
import math
def f(x):
return math.exp(-x) - x
def f_derivative(x):
return -math.exp(-x) - 1
def newton_raphson(x0, tol):
fx = f(x0)
while abs(fx) > tol:
fx_derivative = f_derivative(x0)
if fx_derivative == 0:
return None
x1 = x0 - fx / fx_derivative
x0 = x1
fx = f(x0)
return x0
x0 = -2
tol = 1e-6
root = newton_raphson(x0, tol)
print("The root is:", root)
阅读全文