0% found this document useful (0 votes)
5 views

Assignment-4

The document contains Python code implementing numerical methods to find roots of functions, specifically the Newton-Raphson and Bisection methods. It includes function definitions, input handling, and plotting of the functions and their roots. The results from both methods are printed, showing the roots found and the number of iterations taken.

Uploaded by

Sougata Halder
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Assignment-4

The document contains Python code implementing numerical methods to find roots of functions, specifically the Newton-Raphson and Bisection methods. It includes function definitions, input handling, and plotting of the functions and their roots. The results from both methods are printed, showing the roots found and the number of iterations taken.

Uploaded by

Sougata Halder
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

In [2]: import numpy as np

import matplotlib.pyplot as plt


In [1]: import numpy as np

def f(x):
def f(x):
return x**2 - 4*x + np.exp(-x)
return x**3 - 4*x - 9 # Example function

# Get input for x1 and x2


def df(x):
x1, x2 = map(float, input("Enter x1 and x2: ").split())
return 3*x**2 - 4 # Derivative of the function
a = x1
b = x2
def newton_raphson(x0, tol=1e-6, max_iter=100):
x = x0
def bisection(x1, x2):
iterations = 0
if f(x1) * f(x2) < 0: # Check if root exists in the interval
while iterations < max_iter:
while abs(x1 - x2) > 1e-6: # Improved tolerance for better accuracy
fx = f(x)
mid = (x1 + x2) / 2
dfx = df(x)
if f(x1) * f(mid) < 0:
if abs(dfx) < 1e-10: # Avoid division by zero
x2 = mid
print("Derivative too small, stopping iteration.")
else:
break
x1 = mid
x_new = x - fx / dfx
return mid
if abs(x_new - x) < tol:
else:
return x_new, iterations
return None
x = x_new
iterations += 1
root = bisection(x1, x2)
return x, iterations

if root is None: # Corrected case-sensitivity for None comparison


def bisection(a, b, tol=1e-6, max_iter=100):
print(f'There is no root in this interval [{a}, {b}]')
if f(a) * f(b) >= 0:
else:
raise ValueError("Function values at the endpoints must have opposite signs.")
print(f'The root in this interval [{a}, {b}] is at {root}')
iterations = 0
while (b - a) / 2 > tol and iterations < max_iter:
x = np.linspace(-5, 7, 2000)
c = (a + b) / 2
y = f(x)
if f(c) == 0:
return c, iterations
plt.plot(x, y, label=r'$x^2 - 4x + e^{-x}$', color='blue')
elif f(a) * f(c) < 0:
plt.axhline(0, color='black', linewidth=0.8, linestyle='--') # Add x-axis
b = c
plt.axvline(0, color='black', linewidth=0.8, linestyle='--') # Add y-axis
else:
a = c
# Mark the root if it exists
iterations += 1
if root is not None:
return (a + b) / 2, iterations
plt.plot(root, 0, 'go') # Mark the root on the graph
plt.text(root - 1, 7, f'({root:.2f}, 0)', color='green', fontsize=10, ha='cent
# Initial guess for Newton-Raphson
x0 = 2 # Initial guess
plt.title('$x^2 - 4x + e^{-x}$ vs x')
plt.xlabel('x')
# Interval for Bisection Method
plt.ylabel('f(x)')
a, b = 2, 3
plt.legend(fontsize=12)
plt.grid(True, linestyle='--', alpha=0.6)
# Compute roots using both methods
plt.show()
root_nr, iter_nr = newton_raphson(x0)
root_bisect, iter_bisect = bisection(a, b) The root in this interval [3.0, 5.0] is at 3.995394706726074

print(f"Newton-Raphson Method: Root = {root_nr}, Iterations = {iter_nr}")


print(f"Bisection Method: Root = {root_bisect}, Iterations = {iter_bisect}")

Newton-Raphson Method: Root = 2.706527954497935, Iterations = 5


Bisection Method: Root = 2.706528663635254, Iterations = 19
def f_prime(x):
return 3*x**2 - 2.4*x - 8.19

def newton_raphson(x0, tol=1e-4, max_iter=100):


x = x0
for _ in range(max_iter):
fx = f(x)
fpx = f_prime(x)
if abs(fpx) < 1e-6:
raise ValueError("Derivative too close to zero, Newton-Raphson may not
x_new = x - fx / fpx
if abs(x_new - x) < tol:
return round(x_new, 4)
x = x_new
raise ValueError("Newton-Raphson did not converge within the iteration limit."

# Initial guess
x0 = 2.0
root = newton_raphson(x0)
print("Root found:", root)

Root found: 2.0999

In [ ]:

In [3]: import numpy as np

def f(x):
return x**2 - 4*x + np.exp(-x)

def df(x): # Derivative of f(x)


return 2*x - 4 - np.exp(-x)

def newton_raphson(x0, tol=1e-6, max_iter=100):


x = x0
for _ in range(max_iter):
fx = f(x)
dfx = df(x)
if abs(fx) < tol:
return x
if dfx == 0:
raise ValueError("Derivative is zero. No solution found.")
x -= fx / dfx
raise ValueError("Maximum iterations reached. No solution found.")

# Initial guess
x0 = 2.0
root = newton_raphson(x0)
print(f"Root: {root:.6f}")

Root: 0.213348

In [4]: def f(x):


return x**3 - 1.2*x**2 - 8.19*x + 13.23

You might also like