Python Codes for root finding
Python Codes for root finding
import math
val=int(input())
#Newton Method
def f(x):
return x ** 3 - 5 * x - 9
def g(x):
return Derivative(3 * x ** 2 - 5)
x1 = x0 - f(x0) / g(x0)
print('Iteration-%d, x1 = %0.6f and f(x1) = %0.6f' % (step, x1,
f(x1)))
x0 = x1
step = step + 1
if step > N:
flag = 0
break
if flag == 1:
print('\nRequired root is: %0.8f' % x1)
else:
print('\nNot Convergent.')
#secant method
def secant(x0, x1, e, N):
step = 1
condition = True
while condition:
if f(x0) == f(x1):
print('Divide by zero error!')
break
if step > N:
print('Not Convergent!')
break
step = step + 1
if step > N:
flag = 0
break
if flag == 1:
print('\nRequired root is: %0.8f' % x1)
else:
print('\nNot Convergent.')
#bisection method
def bisection(x0, x1, e):
step = 1
condition = True
while condition:
x2 = (x0 + x1) / 2
print('Iteration-%d, x2 = %0.6f and f(x2) = %0.6f' % (step, x2,
f(x2)))
step = step + 1
condition = abs(f(x2)) > e
step = step + 1
condition = abs(f(x2)) > e
x0 = float(x0)
e = float(e)
N = int(N)
newtonRaphson(x0, e, N)
elif val==2:
x0 = input('Enter First Guess: ')
x1 = input('Enter Second Guess: ')
e = input('Tolerable Error: ')
N = input('Maximum Step: ')
x0 = float(x0)
x1 = float(x1)
e = float(e)
N = int(N)
secant(x0, x1, e, N)
elif val==3:
x0 = float(x0)
e = float(e)
N = int(N)
fixedPointIteration(x0, e, N)
elif val==4:
x0 = input('First Guess: ')
x1 = input('Second Guess: ')
e = input('Tolerable Error: ')
x0 = float(x0)
x1 = float(x1)
e = float(e)
x0 = float(x0)
x1 = float(x1)
e = float(e)
else:
print("Wrong Input! Please select a valid option.")