Python调用二分法和牛顿法求方程的根
作者:野牛程序员:2023-07-25 20:49:09python阅读 2638
以下是使用Python实现二分法和牛顿法求解方程根的示例代码:
二分法:
二分法是一种通过重复将区间一分为二来找出连续函数根的迭代算法。
def bisection_method(func, a, b, tol=1e-6, max_iter=1000): if func(a) * func(b) >= 0: raise ValueError("The function values at the interval endpoints must have opposite signs.") for i in range(max_iter): c = (a + b) / 2 if abs(func(c)) < tol: return c if func(a) * func(c) < 0: b = c else: a = c raise ValueError("Maximum number of iterations exceeded.") # 示例使用 def equation(x): return x**2 - 4 root = bisection_method(equation, 0, 3) print("根为:", root)
牛顿法:
牛顿法是一种迭代算法,通过在函数图像上不断选择切线与x轴的交点,以逼近方程根。
def newton_method(func, derivative_func, x0, tol=1e-6, max_iter=1000): x = x0 for i in range(max_iter): x_new = x - func(x) / derivative_func(x) if abs(x_new - x) < tol: return x_new x = x_new raise ValueError("Maximum number of iterations exceeded.") # 示例使用 def equation(x): return x**2 - 4 def derivative_equation(x): return 2 * x root = newton_method(equation, derivative_equation, 2) print("根为:", root)
请注意,这些代码只是简单的示例,可能不适用于所有情况。在实际使用中,需要根据特定问题进行调整和优化,并考虑处理可能的异常情况。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:Python二分法求方程的根
- 下一篇:使用树莓派PICO点灯