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

LAB5.ipynb - Colab

PYTHON LAB COLAB

Uploaded by

soham.im22
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 views

LAB5.ipynb - Colab

PYTHON LAB COLAB

Uploaded by

soham.im22
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

6/17/24, 6:29 PM LAB5.

ipynb - Colab

keyboard_arrow_down False Position Method


def f(x):
return x**3 - 2*x -5

def false_position(a, b, tol=0.001, max_iter=100):


if f(a) * f(b) >= 0:
print("False Position method fails.")
return None

iter_count = 0
while abs(b - a) >= tol:
c = (a*f(b) - b*f(a)) / (f(b) - f(a))

if f(c) == 0:
break

if f(c) * f(a) < 0:


b = c
else:
a = c

iter_count += 1

if iter_count >= max_iter:


print("Maximum iterations reached.")
break

return round(c, 3)

a = 2
b = 3

root = false_position(a, b)
if root is not None:
print("Root:", root)

Maximum iterations reached.


Root: 2.095

https://colab.research.google.com/drive/17-UPrm1fSOHbNERmCPCBX6Vl6wnsxWqK 1/3
6/17/24, 6:29 PM LAB5.ipynb - Colab

keyboard_arrow_down Newton Raphson Method


def f(x):
return x**3 - 4*x - 9 # Define your function here

def f_prime(x):
return 3*x**2 - 4 # Define the derivative of your function here

def newton_raphson(x0, tol=0.001, max_iter=100):


iter_count = 0
while True:
x1 = x0 - f(x0) / f_prime(x0)
if abs(x1 - x0) < tol:
break
x0 = x1
iter_count += 1

if iter_count >= max_iter:


print("Maximum iterations reached.")
break

return round(x1, 3)

# Initial guess
x0 = 2

root = newton_raphson(x0)
print("Root:", root)

Root: 2.707

keyboard_arrow_down Eulers Method

https://colab.research.google.com/drive/17-UPrm1fSOHbNERmCPCBX6Vl6wnsxWqK 2/3
6/17/24, 6:29 PM LAB5.ipynb - Colab

def f(x):
return x**3 - 4*x - 9 # Define your function here

def f_prime(x):
return 3*x**2 - 4 # Define the derivative of your function here

def newton_raphson(x0, tol=0.001, max_iter=100):


iter_count = 0
while True:
x1 = x0 - f(x0) / f_prime(x0)
if abs(x1 - x0) < tol:
break
x0 = x1
iter_count += 1

if iter_count >= max_iter:


print("Maximum iterations reached.")
break

return round(x1, 3)

# Initial guess
x0 = 2

root = newton_raphson(x0)
print("Root:", root)

Approximate root: 2.0

https://colab.research.google.com/drive/17-UPrm1fSOHbNERmCPCBX6Vl6wnsxWqK 3/3

You might also like