Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

MTH 375 NUMERICAL COMPUTATION

Lab Report-01

Student Name Shah Fahad Khan

FA20-BEE-227

Registration Number
7-A

Class/Section
Dr. Iftikhar Ahmed
Instructor’s Name

Lab Assessment Marks

Pre Lab /1
/1
Ability to use software /5
Follow procedures /5 /10
In Lab
Troubleshoot software /5 /5
Q&A /5
Presentation /4
Post-Lab Analysis /4 /4
Writing /4

COMSATS University Islamabad (CUI), Islamabad Campus Page 1


CODE:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Define the function f(x)
def f(x):
return x**3 - 7*x**2 + 14*x - 6
# Input initial guesses a and b
a = float(input("Enter initial guess for 'a': "))
b = float(input("Enter initial guess for 'b': "))
# Input tolerance

COMSATS University Islamabad (CUI), Islamabad Campus Page 2


e = float(input("Enter tolerance (e.g., 1e-6): "))
# Initialize lists to store iteration data
iteration = []
a_values = []
b_values = []
mid_values = []
f_mid_values = []

# Bisection Method to find the root


while abs(b - a) > e:
mid = (a + b) / 2
f_mid = f(mid)

# Append data to lists


iteration.append(len(iteration) + 1)
a_values.append(a)
b_values.append(b)
mid_values.append(mid)
f_mid_values.append(f_mid)

if f_mid == 0:
break
if f(a) * f_mid < 0:
b = mid
else:
a = mid

root = (a + b) / 2

# Create a DataFrame to display the iteration data


data = {
'Iteration': iteration,
'a': a_values,
'b': b_values,
'Midpoint (x)': mid_values,
'f(Midpoint)': f_mid_values
}
df = pd.DataFrame(data)
# Print the iteration table
print("Iteration Data:")
print(df)
# Generate x values for the plot

COMSATS University Islamabad (CUI), Islamabad Campus Page 3


x_values = np.linspace(0, 1, 400)
y_values = f(x_values)
# Plot the function and the root
plt.plot(x_values, y_values, label='f(x) = $x^3 - 7x^2 + 14x - 6$')
plt.axhline(0, color='red', linestyle='--', linewidth=1, label='y = 0 (Root)')
plt.scatter(root, 0, color='green', label=f'Approximate Root: x = {root:.6f}')
# Add labels and legend
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Graph of f(x) and Approximate Root')
plt.legend()
# Show the plot
plt.grid(True)
plt.show()
print(f"The root is approximately {root:.6f}")

RESULTS:

GRAPH:

COMSATS University Islamabad (CUI), Islamabad Campus Page 4


COMSATS University Islamabad (CUI), Islamabad Campus Page 5

You might also like