In: Computer Science
***Please code in Python
Write another code Newton (in double precision)
implementing the Newton-Raphson Method
(copy your Bisect code and modify).
Evaluation of F(x) and F'(x) should be done in a
subprogram FCN(x).
The code should ask for input of: x0, TOL, maxIT
(and should print output similar to Bisect code).
Debug on a simple problem, like x2−3 = 0.
Then use it to find root of F(x) in [1,2] with
TOL=1.e-12.
Now consider the problem of finding zeros of
G(x) = x−tan(x) near x=99 (radians).
Are there any ? How many ? How do you know ?
Use your Newton code to find the zero of G(x) closest to x = 99
(radians) to 9 decimals ( use
TOL=10−9,maxIT=20
).
Output your final approximate root, the residual, and how many
iterations it took.
THIS IS MY CURRENT CODE FOR BISECTION:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import fsolve
from scipy.misc import derivative
def func(x):
return x*x*x+2*x*x+10*x-20;
def bisection(a,b,tol,maxit):
if (func(a) * func(b) >= 0):
print("You have not assumed right a and b\n")
return
c = a
ct=0;
while ((b-a) >= tol):
ct=ct+1;
# Find middle point
c = (a+b)/2
# Check if middle point is root
if (func(c) == 0.0):
break
# Decide the side to repeat the steps
if (func(c)*func(a) < 0):
b = c
else:
a = c
print("%d"%ct,end='');
print("\t%f"%c,end='');
print("\t%e"%func(c),end='');
print("\t%e"%(b-a),end='\n');
if(ct==maxit):
break;
print("root=%f"%c,end="");
print(", residual=%e"%(b-a),end="");
print(", in%d"%ct,end="");
print(" iters",end="\n");
# Driver code
# Initial values assumed
a =float(input("Enter a: "))
b = float(input("Enter b: "));
tol=float(input("Enter tol: "));
maxit=int(input("Enter maxit: "));
bisection(a, b,tol,maxit)
def func( x ):
return x * x * x - x * x + 2
# Derivative of the above function
# which is 3*x^x - 2*x
def derivFunc( x ):
return 3 * x * x - 2 * x
# Function to find the root
def newtonRaphson( x ):
h = func(x) / derivFunc(x)
while abs(h) >= 0.0001:
h = func(x)/derivFunc(x)
# x(i+1) = x(i) - f(x) / f'(x)
x = x - h
print("The value of the root is : ",
"%.4f"% x)
# Driver program to test above
x0 = -20 # Initial values assumed
newtonRaphson(x0)