目录
非线性方程举例:


非线性方程式求根是一个重要的数值计算问题,常用的方法包括二分法、迭代法和牛顿迭代法。
(连续函数介值定理)
二分法是一种简单而直观的求根方法,适用于单调函数的根。它的基本思想是通过不断缩小根所在区间来逼近根的位置。具体步骤如下:
- def f(x):
- return 5 * x**4 + 3 * x + 1
-
- def bisection_method(a, b, tolerance=1e-6, max_iterations=100):
- if f(a) * f(b) >= 0:
- return None
-
- for _ in range(max_iterations):
- c = (a + b) / 2
- if abs(f(c)) < tolerance:
- return c
-
- if f(c) * f(a) < 0:
- b = c
- else:
- a = c
-
- return None
-
- # 调用二分法求解方程的根
- root = bisection_method(a=-1, b=0)
- if root is not None:
- print("方程的一个根为:", root)
- else:
- print("未找到方程的根")
注意,二分法要求初始区间[a, b]满足f(a) * f(b) < 0,即方程在区间的两个端点上取值异号。
输出:
a=-0.5, b=1
方程的一个根为: -0.36193275451660156
a=-1, b=0
未找到方程的根
迭代法是一种通过不断迭代逼近根的方法,适用于任意函数的根。它的基本思想是从一个初始的近似值开始,通过不断更新逼近根的位置,直到满足预设的精度要求。具体步骤如下:
- def g(x):
- return (-1) / (5 * x**3 + 3)
-
- def iterative_method(initial_guess, tolerance=1e-6, max_iterations=100):
- x = initial_guess
- for _ in range(max_iterations):
- x_next = g(x)
- if abs(x_next - x) < tolerance:
- return x_next
- x = x_next
- return None
-
- # 调用迭代法求解方程的根
- root = iterative_method(initial_guess=0)
- if root is not None:
- print("方程的一个根为:", root)
- else:
- print("未找到方程的根")
注意,迭代法的收敛性与迭代函数的选择密切相关,对于某些函数可能无法收敛或者收敛速度很慢。
输出:
方程的一个根为: -0.36193292438672897
牛顿迭代法是一种快速收敛的求根方法,适用于光滑函数的根。它利用函数的局部线性近似来逼近根的位置。具体步骤如下:
- def f(x):
- return 5 * x**4 + 3 * x + 1
-
- def f_prime(x):
- return 20 * x**3 + 3
-
- def newton_method(initial_guess, tolerance=1e-6, max_iterations=100):
- x = initial_guess
- for _ in range(max_iterations):
- delta_x = f(x) / f_prime(x)
- x -= delta_x
- if abs(delta_x) < tolerance:
- return x
- return None
-
- # 调用牛顿迭代法求解方程的根
- root = newton_method(initial_guess=0)
- if root is not None:
- print("方程的一个根为:", root)
- print(int(f(root)))
- else:
- print("未找到方程的根")
注意,牛顿法要求2阶导不编号,1阶导不为0
输出:
方程的一个根为: -0.3619330489831212
