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

MATH lab final code

The document contains various Python functions for numerical methods, including Lagrange interpolation, bisection method, false position method, and Newton's interpolation. It also covers matrix operations for relations, graph coloring using the Welsh-Powell algorithm, and the Floyd-Warshall algorithm for shortest paths. Additionally, it includes forward and backward difference methods for interpolation.

Uploaded by

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

MATH lab final code

The document contains various Python functions for numerical methods, including Lagrange interpolation, bisection method, false position method, and Newton's interpolation. It also covers matrix operations for relations, graph coloring using the Welsh-Powell algorithm, and the Floyd-Warshall algorithm for shortest paths. Additionally, it includes forward and backward difference methods for interpolation.

Uploaded by

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

9.

def lagrange_interpolation(x_values, y_values, x):

n = len(x_values)
result = 0

for i in range(n):
term = y_values[i]
for j in range(n):
if i != j:
term *= (x - x_values[j]) / (x_values[i] -
x_values[j])
result += term

return result

# Given data points


x_values = [5, 6, 9, 11]
y_values = [12, 13, 14, 16]
x = 10 # The value to interpolate

# Compute the interpolated value


y_interpolated = lagrange_interpolation(x_values, y_values, x)
print(f"Interpolated value at x={x} is y={y_interpolated:.4f}")

10. def f(x):

return x**2 - 4*x - 10 # Given function

def bisection_method(a, b, tol=1e-6):


if f(a) * f(b) >= 0:
print("Bisection method fails. The function must have opposite
signs at a and b.")
return None

while (b - a) / 2.0 > tol:


c = (a + b) / 2.0
if f(c) == 0:
return c # Found exact root
elif f(a) * f(c) < 0:
b = c # Root lies in [a, c]
else:
a = c # Root lies in [c, b]

return (a + b) / 2.0 # Return approximate root

# Given interval
a = -2
b = -1.5

# Find root
root = bisection_method(a, b)
if root is not None:
print(f"Approximate root in the interval [{a}, {b}]: {root:.6f}")

11. def f(x):

return x**2 - x - 2 # Given function

def false_position(a, b, tol=1e-6, max_iter=100):


if f(a) * f(b) >= 0:
print("Invalid interval, f(a) and f(b) must have opposite
signs")
return None

for _ in range(max_iter):
# Compute the root using false position formula
c = (a * f(b) - b * f(a)) / (f(b) - f(a))

if abs(f(c)) < tol:


return c # Root found

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


b = c # Root lies in left subinterval
else:
a = c # Root lies in right subinterval

print("Maximum iterations reached")


return c

# Given range (1,3)


root = false_position(1, 3)
if root is not None:
print(f"Root found: {root:.6f}")

8. def divided_difference_table(x, y):


n = len(x)
table = [[0 for _ in range(n)] for _ in range(n)]

# Initialize the first column with y values


for i in range(n):
table[i][0] = y[i]

# Calculate divided differences


for col in range(1, n):
for row in range(n - col):
table[row][col] = (table[row + 1][col - 1] -
table[row][col - 1]) / (x[row + col] - x[row])

return table

def newton_interpolation(x, y, value):


table = divided_difference_table(x, y)
n = len(x)
result = table[0][0]
term = 1

for i in range(1, n):


term *= (value - x[i - 1])
result += term * table[0][i]

return result
# Example usage
x = [4, 5, 7, 10, 11, 13]
y = [48, 100, 294, 900, 1210, 2028]
value = 15

print("Interpolated value at", value, "is:", newton_interpolation(x,


y, value))

1. def find_relations(A):
"""Finds relations R1 and R2 on set A."""
R1 = [] # Relation where a divides b
R2 = [] # Relation where a <= b

for a in A:
for b in A:
if b % a == 0: # Check if a divides b
R1.append((a, b))
if a <= b:
R2.append((a, b))

return R1, R2

A = {1, 2, 3, 4}
R1, R2 = find_relations(A)

print("Relation R1 (a divides b):", R1)


print("Relation R2 (a <= b):", R2)

2. def find_relation_and_matrix(A, B):


"""Finds the relation R and its matrix representation."""
R = [] # Relation where a > b

for a in A:
for b in B:
if a > b:
R.append((a, b))

# Matrix Representation
matrix = [[0 for _ in B] for _ in A] # Initialize matrix with 0s

for a, b in R:
matrix[A.index(a)][B.index(b)] = 1 # Set matrix element to 1
if (a, b) is in R

return R, matrix

A = [1, 2, 3]
B = [1, 2]
R, matrix = find_relation_and_matrix(A, B)

print("Relation R (a > b):", R)


print("Matrix Representation:")
for row in matrix:
print(row)

5. def matrix_union(MR1, MR2):


"""Calculates the union of two relation matrices."""
rows = len(MR1)
cols = len(MR1[0])
union_matrix = [[0 for _ in range(cols)] for _ in range(rows)]

for i in range(rows):
for j in range(cols):
union_matrix[i][j] = MR1[i][j] or MR2[i][j]

return union_matrix

def matrix_intersection(MR1, MR2):


"""Calculates the intersection of two relation matrices."""
rows = len(MR1)
cols = len(MR1[0])
intersection_matrix = [[0 for _ in range(cols)] for _ in
range(rows)]

for i in range(rows):
for j in range(cols):
intersection_matrix[i][j] = MR1[i][j] and MR2[i][j]

return intersection_matrix

MR1 = [[1, 0, 1], [1, 0, 0], [0, 1, 0]]


MR2 = [[1, 0, 1], [0, 1, 1], [1, 0, 0]]

union_result = matrix_union(MR1, MR2)


composition_result = matrix_intersection(MR1, MR2)

print("MR1 ∪ MR2:")
for row in union_result:
print(row)

print("\nMR1 ∩ MR2:")
for row in composition_result:
print(row)

3. class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0] * vertices for _ in range(vertices)]

def add_edge(self, u, v):


self.graph[u][v] = 1
self.graph[v][u] = 1

def welsh_powell_coloring(self):
# Sort vertices by degree (number of connections)
degree_list = sorted(range(self.V), key=lambda v:
sum(self.graph[v]), reverse=True)
colors = [-1] * self.V # -1 means uncolored
color = 0

for vertex in degree_list:


if colors[vertex] == -1: # If uncolored
colors[vertex] = color

# Assign the same color to non-adjacent vertices


for other in degree_list:
if colors[other] == -1 and
all(self.graph[other][k] == 0 or colors[k] != color for k in
range(self.V)):
colors[other] = color

color += 1

return colors

# Example usage
g = Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(1, 4)
g.add_edge(2, 3)
g.add_edge(3, 4)

coloring = g.welsh_powell_coloring()
print("Vertex Colors:", coloring)

4. INF = float('inf')

def floyd_warshall(graph):
V = len(graph)
dist = [row[:] for row in graph] # Copy of the graph

for k in range(V):
for i in range(V):
for j in range(V):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

return dist

# Example graph (adjacency matrix)


graph = [
[0, 3, INF, INF],
[INF, 0, 2, INF],
[INF, INF, 0, 1],
[8, INF, INF, 0]
]

shortest_paths = floyd_warshall(graph)
for row in shortest_paths:
print(row)

6. import numpy as np

def forward_difference(y_values):
n = len(y_values)
table = np.zeros((n, n))
table[:, 0] = y_values

for j in range(1, n):


table[:n-j, j] = table[1:n-j+1, j-1] - table[:n-j, j-1]

return table

def newton_gregory(x_values, y_values, x):


h = x_values[1] - x_values[0]
u = (x - x_values[0]) / h

table = forward_difference(y_values)
result, u_term, fact = y_values[0], 1, 1
for i in range(1, len(x_values)):
u_term *= (u - (i - 1))
fact *= i
result += (u_term / fact) * table[0][i]

return result

# Given data
years = np.array([1911, 1921, 1931, 1941, 1951, 1961])
population = np.array([12, 15, 20, 27, 39, 52])

year_to_predict = 1946
print(f"Estimated population in {year_to_predict}:
{newton_gregory(years, population, year_to_predict):.2f}")

7. import numpy as np

def backward_difference(y_values):
n = len(y_values)
table = np.zeros((n, n))
table[:, 0] = y_values

for j in range(1, n):


table[j:, j] = table[j:, j-1] - table[j-1:-1, j-1]

return table

def newton_gregory_backward(x_values, y_values, x):


h = x_values[1] - x_values[0]
u = (x - x_values[-1]) / h

table = backward_difference(y_values)
result, u_term, fact = y_values[-1], 1, 1

for i in range(1, len(x_values)):


u_term *= (u + (i - 1))
fact *= i
result += (u_term / fact) * table[-1][i]

return result

# Given data
x_vals = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y_vals = np.array([1, 8, 27, 64, 125, 216, 343, 512])

x_to_predict = 7.5
print(f"Estimated value at f({x_to_predict}):
{newton_gregory_backward(x_vals, y_vals, x_to_predict):.2f}")

You might also like