0% found this document useful (0 votes)
31 views11 pages

Lab 02 NC

The document describes Newton's method and secant method for finding roots of nonlinear equations numerically. It provides definitions, algorithms, advantages and disadvantages of both methods. Code examples in Python are given to implement the methods to solve a sample equation along with plotting the iterations.

Uploaded by

haiderkomail113
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views11 pages

Lab 02 NC

The document describes Newton's method and secant method for finding roots of nonlinear equations numerically. It provides definitions, algorithms, advantages and disadvantages of both methods. Code examples in Python are given to implement the methods to solve a sample equation along with plotting the iterations.

Uploaded by

haiderkomail113
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Numerical Computation MTH375

Lab Report-02

Student Name Kumail Haider

Registration FA20-BEE-088
Number

Class/Section 7TH- B

Instructor’s Name DR. Iftikhar Ahmad

1
Newton’s Method
Definition:
The Newton-Raphson method is a numerical technique for finding
roots of real-valued functions. It iteratively refines estimates based
on linear approximation.

The Method:
• Starts with an initial guess x0.

• Iteratively refines the estimate: xn+1=xn−f′(xn)f(xn)

• Convergence is generally quadratic.

2
Algorithm:
• Choose an initial guess x0.

• Iterate using the formula until convergence.

• Stop when the change in x is small or after a set number of


iterations

🌟 Advantages

1. Fast Convergence: Newton Raphson converges rapidly, especially


with a good initial guess.

2. Efficiency: Effective for smooth and well-behaved functions.

3. Adaptive Steps: Utilizes second derivatives for adaptive step sizes,


contributing to efficiency.

3
🚫 Disadvantages

1. Convergence Challenges: Slow convergence or divergence with a poor


initial guess.

2. Function Dependency: May fail for functions with multiple roots or


discontinuities.

3. Computational Cost: Computationally expensive, requiring the derivative


and solving a linear system at each iteration.

Question: Find the solution of the following nonlinear equation by using


Newton’s Method
𝑥^3−𝑥^2+7𝑥−9
Code the Newton’s Method Using Python:
def newton(f, df, xo, E, N):
iteration_table = []
for i in range(N):
f_val = f(xo)
df_val = df(xo)
xo_new = xo - f_val / df_val
iteration_table.append([i+1, xo, f_val, df_val, xo_new])

if abs(xo_new - xo) < E:


break

xo = xo_new

return xo_new, iteration_table

# Define the function and its derivative

4
def f(x):
return x**3 - x**2 + 7*x - 9

def df(x):
return 3*x**2 - 2*x + 7

# Input initial guess and other parameters


xo = float(input("Enter initial guess xo: "))
E = float(input("Enter tolerance E: "))
N = int(input("Enter the number of iterations N: "))

# Call the Newton's method function


solution, table = newton(f, df, xo, E, N)

# Print the solution and iteration table


print("\nSolution:", solution)
print("\nIteration Table:")
print("Iter | xo\t\t| f(xo)\t\t| f'(xo)\t| xo_new")
for row in table:
print(f"{row[0]}\t| {row[1]:.6f}\t| {row[2]:.6f}\t| {row[3]:.6f}\t| {row[4]:.6f}")

Output:

5
Plot
import numpy as np
import matplotlib.pyplot as plt

def newton(f, df, xo, E, N):


iteration_points = [xo]
for i in range(N):
f_val = f(xo)
df_val = df(xo)
xo_new = xo - f_val / df_val
iteration_points.append(xo_new)

if abs(xo_new - xo) < E:


break

xo = xo_new

return iteration_points

# Define the function and its derivative


def f(x):
return x**3 - x**2 + 7*x - 9

def df(x):
return 3*x**2 - 2*x + 7

# Input parameters
xo = 2
E = 0.00001
N=5

# Call the Newton's method function


points = newton(f, df, xo, E, N)

# Generate x values for plotting


x_values = np.linspace(min(points) - 1, max(points) + 1, 100)
y_values = f(x_values)

# Plot the function and the iteration points


plt.plot(x_values, y_values, label="f(x)")
plt.scatter(points, [f(p) for p in points], color='red', label="Iteration Points")

6
plt.title("Newton's Method Iterations for f(x)")
plt.xlabel("x")
plt.ylabel("f(x)")
plt.legend()
plt.grid(True)
plt.show()
Output:

7
Secant Method
Definition
The Secant Method is a numerical technique used for finding the roots of a real-valued
function. It's an iterative process that refines the estimation of the root by approximating
the slope of the function at two successive points. Unlike the Newton-Raphson method,
the Secant Method doesn't require explicit calculation of derivatives.
The Method
1. Algorithm:

• Choose two initial guesses xo and x1 such that


• Iteratively update the approximation using the formula:

• Repeat until the desired level of accuracy is reached.


Secant Method Advantages
1. No Derivative Required:
• The method doesn't necessitate the calculation of derivatives, making it
applicable to a broader range of functions.
2. Faster Convergence:
• The Secant Method converges faster than linear methods, such as the
bisection method.
3. Simplicity:
• It is relatively simple to implement compared to methods that require
derivative evaluations.
Secant Method Disadvantages
1. Convergence Sensitivity:
• The method may exhibit sensitivity to the choice of initial guesses, affecting
convergence.

8
2. Potential for Divergence:
• If the initial points are chosen poorly, the method might diverge instead of
converging.
3. No Guaranteed Convergence:
• Unlike some methods, the Secant Method doesn't guarantee convergence to a
solution.

Question: Find the solution of the following nonlinear equation by using


secant’s Method
𝑥^3−𝑥^2+7𝑥−9
Code the secant’s Method Using Python:
def secant(f, x0, x1, E, N):
print(f"Iteration\t{x0}\t\t{x1}\t\tRoot Approximation")
for i in range(1, N + 1):
f_x0 = f(x0)
f_x1 = f(x1)
root_approximation = x1 - (f_x1 * (x1 - x0)) / (f_x1 - f_x0)

print(f"{i}\t\t\t{x0:.6f}\t{x1:.6f}\t{root_approximation:.6f}")

if abs(root_approximation - x1) < E:


print(f"\nRoot found at iteration {i}: {root_approximation}")
return root_approximation

x0, x1 = x1, root_approximation


print("\nFailed to converge within the given number of iterations.")
return None
# Example Usage
def equation(x):
return x**3 - x**2 + 7*x - 9
# User inputs
initial_guess_1 = float(input("Enter the first initial guess (xo): "))
initial_guess_2 = float(input("Enter the second initial guess (x1): "))
tolerance = float(input("Enter the tolerance (E): "))
max_iterations = int(input("Enter the maximum number of iterations (N): "))
# Calling the secant method
secant(equation, initial_guess_1, initial_guess_2, tolerance, max_iterations)

9
Output:

Code for Plot


import numpy as np
import matplotlib.pyplot as plt

def secant(f, x0, x1, E, N):


iterations = []
for i in range(1, N + 1):
f_x0 = f(x0)
f_x1 = f(x1)

root_approximation = x1 - (f_x1 * (x1 - x0)) / (f_x1 - f_x0)

iterations.append(root_approximation)

if abs(root_approximation - x1) < E:


print(f"\nRoot found at iteration {i}: {root_approximation}")
return iterations

x0, x1 = x1, root_approximation

print("\nFailed to converge within the given number of iterations.")


return iterations

def plot_iterations(f, x_values):


x = np.arange(len(x_values))
y = np.array(x_values)

10
plt.plot(x, y, marker='o', linestyle='-', color='b')
plt.title("Secant Method Iterations")
plt.xlabel("Iteration")
plt.ylabel("Root Approximation")
plt.grid(True)
plt.show()

# Example Usage
def equation(x):
return x**3 - x**2 + 7*x - 9

# User inputs
initial_guess_1 = float(input("Enter the first initial guess (xo): "))
initial_guess_2 = float(input("Enter the second initial guess (x1): "))
tolerance = float(input("Enter the tolerance (E): "))
max_iterations = int(input("Enter the maximum number of iterations (N): "))

# Calling the secant method


iterations = secant(equation, initial_guess_1, initial_guess_2, tolerance, max_iterations)

# Plotting the iterations


plot_iterations(equation, iterations)

Plot

11

You might also like