Home  >  Article  >  Backend Development  >  How to find the roots of an equation using python bisection method

How to find the roots of an equation using python bisection method

PHPz
PHPzforward
2024-03-01 14:43:241250browse

How to find the roots of an equation using python bisection method

To use the bisection method to solve the roots of an equation, you can follow these steps:

  1. Define a function to calculate the value of the equation. Assuming that the equation we want to solve is f(x)=0, then this function can be written in the form of def f(x):.

  2. Determine the search range of dichotomy. Based on the properties of the equation, choose a left boundary and a right boundary such that f (left boundary) and f (right boundary) have opposite signs. That is, if f(left boundary) is positive and f(right boundary) is negative, or f(left boundary) is negative and f(right boundary) is positive.

  3. Iterate over the search range using the bisection method until the roots of the equation are found. Specific steps are as follows: a. Calculate the midpoint of the search range mid=(left boundary right boundary)/2. b. Calculate the value of f(mid). c. Determine the symbol of f(mid) and update the search range:

    • If f(mid) is 0, it means mid is a root of the equation, and the iteration ends.
    • If the signs of f(mid) and f(left boundary) are the same, it means that the root is on the right half, and the left boundary is updated to mid.
    • If the signs of f(mid) and f(right boundary) are the same, it means that the root is on the left half, and the right boundary is updated to mid. d. Repeat steps a-c until you find the roots of the equation.

The following is a sample code that uses the bisection method to solve the roots of an equation:

def f(x):
# 定义方程的函数
return x**2 - 4

def find_root():
left = -10# 左边界
right = 10# 右边界

while right - left > 1e-6:# 设置迭代的终止条件
mid = (left + right) / 2# 计算中点

if f(mid) == 0:# 如果中点处的函数值为0,说明找到了根
return mid

if f(mid) * f(left) < 0:# 根在左半边
right = mid
else:# 根在右半边
left = mid

return mid

root = find_root()
print("方程的根为:", root)

In the above code, we define an equation f(x)=x^2-4 and use the bisection method to solve the root of the equation. In the while loop, we continuously update the left and right boundaries of the search range until we find the root of the equation. Finally, the value of the root is output.

The above is the detailed content of How to find the roots of an equation using python bisection method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete