AIM: Write a Python program to find the roots of non-linear equation using Bisection method.
Source Code:
#Program for Bisection Method
def f(x):
return x**3 - x**2 + 2
def bisection(x0,x1):
if (f(x0) * f(x1) >= 0.0):
print("You have not assumed right x0 and x1")
return
mid = x0
while ((x1-x0) >= 0.01):
# Find middle point
mid = (x0+x1)/2
# Check if middle point is root
if (f(mid) == 0.0):
break
# Decide the side to repeat the steps
if (f(mid)*f(x0) < 0.0):
x1 = mid
else:
x0 = mid
print("The value of root is : %.2f"%(mid))
x0 = float(input("Enter first value: "))
x1 = float(input("Enter second value: "))
bisection(x0, x1)
Output:def f(x):
return x**3 - x**2 + 2
def bisection(x0,x1):
if (f(x0) * f(x1) >= 0.0):
print("You have not assumed right x0 and x1")
return
mid = x0
while ((x1-x0) >= 0.01):
# Find middle point
mid = (x0+x1)/2
# Check if middle point is root
if (f(mid) == 0.0):
break
# Decide the side to repeat the steps
if (f(mid)*f(x0) < 0.0):
x1 = mid
else:
x0 = mid
print("The value of root is : %.2f"%(mid))
x0 = float(input("Enter first value: "))
x1 = float(input("Enter second value: "))
bisection(x0, x1)
Sample Input1:
Enter first value: -200
Enter second value: 300
Sample Output1:
The value of root is : -1.00
Sample Input2:
Enter first value: 2
Enter second value: 3
Sample Output2:
You have not assumed right x0 and x1
Enter first value: -200
Enter second value: 300
Sample Output1:
The value of root is : -1.00
Sample Input2:
Enter first value: 2
Enter second value: 3
Sample Output2:
You have not assumed right x0 and x1