0% found this document useful (0 votes)
9 views3 pages

Bisection Method Mahalakshmi R

Uploaded by

rmaha1908
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)
9 views3 pages

Bisection Method Mahalakshmi R

Uploaded by

rmaha1908
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/ 3

Code:

print ("Bisection Method")


print ("Mahalakshmi R")

import math
from matplotlib import pyplot as plt
import numpy as np
from datetime import datetime

today = datetime.today()
print(today.strftime("%B %d, %Y"))

# Defining the function f(x)


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

# Bisection method implementation with tolerance


def bis(a, b, tol=1e-5, max_iter=100):
if f(a) * f(b) >= 0:
print("Bisection method fails. The function must have
different signs at a and b.")
return None

iteration = 0
while (b - a) / 2 > tol and iteration < max_iter:
c = (a + b) / 2 # Midpoint
if f(c) == 0 or (b - a) / 2 < tol: # Root found or interval
is small enough
return c
elif f(a) * f(c) < 0: # Root lies between a and c
b = c
else: # Root lies between c and b
a = c
iteration += 1

return (a + b) / 2 # Return the midpoint as the root

# Defining the range for root search


a = -10
b = 10

# Finding the root in two intervals: [-10, 0] and [0, 10]


r = [bis(a, 0), bis(0, b)]

# Filter out None values from roots list


r = [root for root in r if root is not None]

# X-axis range for plotting


x = np.arange(a, b, 0.001)

# Title of the Graph


plt.title("Graphical Representation of f(x) = x^2 + 9^x - 3")

# X-axis label
plt.xlabel("x")

# Y-axis label
plt.ylabel("f(x)")

# Plotting the function f(x)


plt.plot(x, f(x))

# Displaying the root points on the graph


for i in range(len(r)):
res = r[i]
inc = f(r[i])

# Plot the root points


plt.plot(res, inc, 'ro')
plt.text(res, inc, '({:.5f},{:.5f})'.format(res, inc))

# Horizontal line at y=0


plt.axhline(0, color='black', linewidth=0.5)

# Displaying the grid


plt.grid(True)

# Showing the graph


plt.show()

Output:

Bisection Method

Mahalakshmi R

October 22, 2024

You might also like