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

Lab_Changed

The document contains code snippets for various mathematical computations using Python, including vector space checks, plotting ellipses, and generating Cantor sets. It also includes functions to check for Hermitian matrices, perform Gram-Schmidt orthogonalization, and visualize regions defined by norms. The code is structured into different sections, each addressing a specific mathematical concept or problem.

Uploaded by

Arnab Mallick
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)
3 views

Lab_Changed

The document contains code snippets for various mathematical computations using Python, including vector space checks, plotting ellipses, and generating Cantor sets. It also includes functions to check for Hermitian matrices, perform Gram-Schmidt orthogonalization, and visualize regions defined by norms. The code is structured into different sections, each addressing a specific mathematical concept or problem.

Uploaded by

Arnab Mallick
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/ 23

11/26/24, 5:53 PM Lab2.

ipynb - Colab

#Q1

import numpy as np
import random as rand

low = -10
high = 10

############ Part a #############

vspacel = np.empty((0, 3))

for i in range(low, high+1):


for j in range(low, high+1):
for k in range(low, high+1):
if i + j + k == 1:
new_vector = np.array([[i, j, k]])
vspacel = np.vstack((vspacel, new_vector))

vspacel = vspace1.T

def is_vector_space1(vspace):
n = vspace.shape[1]
#Vector addition
for i in range(0, n):
for j in range(0, n):
res = vspace[:, i] + vspace[:, j]
if res[0] + res[1] + res[2] != 1:
print(f'Part a: It is not a vector space')
return 0
#Scalar multiplication
for i in range(0, n):
res = vspace[:, i] * rand.random()
if res[0] + res[1] + res[2] != 1:
print(f'Part a: It is not a vector space')
return 0
print(f'Part a: It is a vector space')
return 1

is_vector_space1(vspacel)

############ Part b ##############

vspace2 = np.empty((0, 3))

for i in range(low, high+1):


for j in range(low, high+1):
for k in range(low, high+1):
if i*i + j*j + k*k == 1:
new vertnr = nn.errzv£fCi. d. klll
https://coIab.research.googIe.com/drive/1xUUMa5p gfF4D9-AftyiOHEKR2-oeHzJ#scroIITo=5qUZORBjYE4U&printMode=true 1/5
11/26/24, 5:53 PM Lab2.ipynb - Colab

vspace2 = np.vstack((vspace2, new_vector))

vspace2 = vspace2.T

def is_vector_space2(vspace):
n = vspace.shape[1]
#Vector addition
for i in range(0, n):
for j in range(0, n):
res = vspace[:, i] + vspace[:, j]
if res[0]**2 + res[1]**2 + res[2]**2 != 1:
print(f'Part b: It is not a vector space')
return 0
#Scalar multiplication
for i in range(0, n):
res = vspace[:, i] * rand.random()
if res[0] + res[1] + res[2] != 1:
print(f'Part a: It is not a vector space')
return 0
print(f'Part b: It is a vector space')
return 1

is_vector_space2(vspace2)

Part a: It is not a vector space


Part b: It is not a vector space
0

#Q4

import numpy as np
import matplotlib.pyplot as plt

# Parameters
a = 3 # Coefficient for v1’B

# Generate parameter t
t = np.linspace(0, 2 * np.pi, 500)

# Coordinates in basis B
v1_B = np.cos(t) / np.sqrt(a)
v2_B = np.sin(t)

# Transform to standard basis


v1 = v1_B
v2 = v2_B

# Plot the ellipse


plt.figure(figsize=(6, 6))

https://coIab.research.googIe.com/drive/1xUUMa5p gfF4D9-AftyiOHEKR2-oeHzJ#scroIITo=5qUZORBjYE4U&printMode=true 2/5


11/26/24, 5:53 PM Lab2.ipynb - Colab
plt.plot(v1, v2, label=f'Ellipse for a = {a}', color='blue')
plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.gca().set_aspect('equal', adjustable='box')
plt.title('Ellipse in Standard Basis')
plt.xlabel('$v_1$')
plt.ylabel('$v_2$')
plt.legend()
plt.grid()
plt.show()

#Q5

import numpy as np
import matplotlib.pyplot as plt

arr = np.array([[0.8, 0.3], [0.2, 0.7]])


vec = np.array([1, 0])
result = np.zeros(shape=(11, 2))

https://coIab.research.googIe.com/drive/1xUUMa5p gfF4D9-AftyiOHEKR2-oeHzJ#scroIITo=5qUZORBjYE4U&printMode=true 3/5


11/26/24, 5:53 PM Lab2.ipynb - Colab

x = np.zeros(shape=10)
y = np.zeros(shape=10)

for k in range(0,10):
for i in range(0,2):
result[k+1][i] = (result[k][0] * arr[0][i]) + (result[k][1] * arr[1][i])
if i == 0:
x[k] = result[k+1][i]
else:
y[k] = result[k+1][i]

plt.plot(x, y)
plt.show()

0.6D

0.55

0.45

0.4D

0.35

0.3D -

0.60D 0.625 0.630 0.675 0.7D0 D.725 D.730 D.775 D.80D

https://colab.research.google.com/drive/1xUUMa5p gfF4D9-AftyiOHEKR2-oeHzJ#scroIlTo=5qUZORBjYE4U&printMode=true 4/5


11/26/24, 5:53 PM Lab2.ipynb - Colab

https://coIab.research.googIe.com/drive/1xUUMa5p gfF4D9-AftyiOHEKR2-oeHzJ#scroIITo=5qUZORBjYE4U&printMode=true 5/5


11/26/24, 5:58 PM Lab3.ipynb - Colab

#Q1

import numpy as np

def is_hermitian(matrix):
”””Check if a given matrix is Hermitian.“”“
return np.array_equal(matrix, matrix.conj().T)

def main():
# Predefined input
rows = [
[1, 2+1j],
[2-1j, 3]

matrix = np.array(rows)

print(“Matrix:“)
print(matrix)

if is_hermitian(matrix):
print(“\nThe given matrix is Hermitian.”)
else:
print(“\nThe given matrix is NOT Hermitian.”)

main()

Matrix:
[[1.+0 j 2.+1.j]
[2.-1.j 3.+0.j]]

The given matrix is Hermitian.

#Q2

import numpy as np

def inner_product(x, y):


”””Custom inner product for R^3.”””
return (

2 * x[0] * y[1] +
2 * x[1] * y[0] +
5 * x[1] * y[1] +
x[2] * y[2]

def gram_schmidt_with_custom_inner(vectors):
”””Apply Gram-Schmidt orthogonalization with a custom inner product.“““

https://coIab.research.googIe.com/drive/1Q0OBmLNGnL3DHtJnMvVQ-gorZIdrFTf5#scroIITo=TR1cnhv7DL8L&printMode=true 1/4
11/26/24, 5:58 PM Lab3.ipynb - Colab
orthogonal_basis = []

for v in vectors:
orthogonal_v = v.copy()
for u in orthogonal_basis:
proj = (inner_product(v, u) / inner_product(u, u)) * np.array(u)
orthogonal_v -= proj
orthogonal_basis.append(orthogonal_v)

return orthogonal_basis

def is_independent(vectors):
”””Check if the set of vectors are linearly independent.”””
matrix = np.array(vectors).T # Form a matrix with vectors as columns
rank = np.linalg.matrix_rank(matrix)
return rank == len(vectors)

def main():
# Input vectors
u1 = np.array([1.0, 0.0, 0.0])
u2 = np.array([1.0, 2.0, 0.0])
u3 = np.array([1.0, 2.0, 3.0])

vectors = [u1, u2, u3]

if not is_independent(vectors):
print(“The vectors are not linearly independent.”)
else:
# First, orthogonalize u1 and u2 to ensure span(u1, u2) = span(v1, v2)
v1, v2 = gram_schmidt_with_custom_inner([u1, u2])[:2]

# Then, orthogonalize u3 relative to v1 and v2


v3 = u3.copy()
for u in [v1, v2]:
proj = (inner_product(u3, u) / inner_product(u, u)) * np.array(u)
v3 -= proj

# The final orthogonal basis


orthogonal_basis = [v1, v2, v3]
print(“The orthogonal basis is:”)
for i, v in enumerate(orthogonal_basis):
print(f“v{i+1} = {v}”)

main ( )

The orthogonal basis is:

v2 = [-4. 2. 0.]
v3 = [0. 0. 3.]

https://coIab.research.googIe.com/drive/1Q0OBmLNGnL3DHtJnMvVQ-gorZIdrFTf5#scroIITo=TR1cnhv7DL8L&printMode=true 2/4
11/26/24, 5:58 PM Lab3.ipynb - Colab

#Q4

import requests
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('Image.png')

# Conventing the image into gray scale fon faster computation.


gray_image = cv2.cvtColor(img, cv2.COL0R_BGR2GRAY)

# Calculating the SVD


u, s, v = np.linalg.svd(gray_image, full_matrices=False)

# plot images with 10% of components


high = s.shape[0]
low = int(high/10)

u_d = u[:, :low]


s_d = s[:low]
v_d = v[:low, :]

recon_image = u_d @ np.diag(s_d) @ v_d

plt.figure(figsize=(12, 6))

plt.subplot(1,2,1)
plt.imshow(gray_image, cmap='gray');
plt.title(f’Actual Image')

plt.subplot(1,2,2)
plt.imshow(recon_image, cmap='gray');
plt.title(f'Reconstnucted Image')

cv2.imwrite('0riginal_image.png', img)
cv2.imwrite('Reconstructed_image.png', recon_image)

https://coIab.research.googIe.com/drive/1Q0OBmLNGnL3DHtJnMvVQ-gorZIdrFTf5#scroIITo=TR1cnhv7DL8L&printMode=true 3/4
11/26/24, 5:58 PM Lab3.ipynb - Colab

Actual lmaqe Reconstructed Image

https://colab.research.google.com/drive/1Q0OBmLNGnL3DHtJnMvVQ-gorZldrFTf5#scrollTo=TR1cnhv7DL8L&printMode=true 4/4
11/26/24, 6:02 PM Lab4.ipynb - Colab

#Q1

def generate_cantor_set(n):
”“”Generate the nth Cantor set E_n.“””
intervals = [(0, 1)] # Start with E_0 = [0, 1]

for _ in range(n):
next_intervals = []
for start, end in intervals:
length = (end - start) / 3
# Add the left third
next_intervals.append((start, start + length))
# Add the right third
next_intervals.append((end - length, end))
intervals = next_intervals

return intervals

def display_intervals(intervals):
”“”Display the intervals in a human-readable format.”””
for interval in intervals:
print(f“[{interval[0]:.6f}, {interval[1]:.6f}]“)

def main(n):
# Generate the Cantor set E_n
cantor_set = generate_cantor_set(n)

print(f“\nThe intervals in E_{n} are:“)


display_intervals(cantor_set)

if enamel == “ main ”:
main(2)

The intervals in E_2 are:


[0.000000, 0.111111]
[0.222222, 0.333333]
[0.666667, 0.777778]
[0.888889, 1.000000]

#Q2

import numpy as np
import matplotlib.pyplot as plt

def plot_region_r():
”””Plot regions defined by (|x1l’r + |x2|’r)’(1/r) ‹= 1 for r = 1, 2, 3.”""
x = np.linspace(-1.5, 1.5, 400)

https://coIab.research.googIe.com/drive/1o7aA1t BIOjD40D8QcP-Kkd22pqqFcI8#scroIITo=9DLTknMMcpEE&printMode=true 1/8


11/26/24, 6:02 PM Lab4.ipynb - Colab
y = np.linspace(-1.5, 1.5, 400)
X, Y = np.meshgrid(x, y)

plt.figure(figsize=(10, 5))

# Loop over r = 1, 2, 3
for i, r in enumerate([1, 2, 3], 1):
Z = (np.abs(X)**r + np.abs(Y)**r)**(1/r)
plt.subplot(1, 3, i)
plt.contourf(X, Y, Z, levels=[0, 1], colors=[“skyblue”])
plt.title(f“r = {r}”)
pit.xlabel(“$x_1$”)
pit.ylabel(“$x_2$”)
pit.axis(“equal”)

plt.tight_layout()
plt.show()

def plot_max_norm():
”"”Plot region defined by max(lx1|, l^2|) <= 1.“““
x = np.linspace(-1.5, 1.5, 400)
y = np.linspace(-1.5, 1.5, 400)
X, Y = np.meshgrid(x, y)

Z = np.maximum(np.abs(X), np.abs(Y))

plt.figure(figsize=(6, 6))
plt.contourf(X, Y, Z, levels=[0, 1], colors=["lightgreen”])
plt.title(r“Region $\max(|x_1|, l^_2l) \leq 1$“)
plt.xlabel(“$x_1$“)
plt.ylabel("$x_2$”)
plt.axis(”equal")
plt.show()

# Main function to call the plots


def main():
print(“Plotting regions for (|x1l’° + l^2|’r)’(1/r) <= 1 (r = 1, 2, 3)...”)
plot_region_r()

print(“Plotting region for max(l*1|, l*2|) <= 1...”)


plot_max_norm()

if enamel == “ main “:
main()

https://coIab.research.googIe.com/drive/1o7aA1t BIOjD40D8QcP-Kkd22pqqFcI8#scroIITo=9DLTknMMcpEE&printMode=true 2/8


11/26/24, 6:02 PM Lab4.ipynb - Colab

-i- Plotting regions for (l*1|’r + l'2|’r)’(1/r) ‹= 1 (r = 1, 2, 3)...


r=1 r=2 r=3

1 -1 0
xl /1
Plotting region for max(|x1l. l'2|) <= 1...
Region max(|x‹I l• I)e 1
1.5

1.0-

0.0-

—0.5 -

—1.D -

https://colab.research.google.com/drive/1o7aA1t BIOjD40D8QcP-Kkd22pqqFcI8#scrollTo=9DLTknMMcpEE&printMode=true 3/8


11/26/24, 6:02 PM Lab4.ipynb - Colab

#Q3

import math

def f(n):
”””Calculate f(n) based on the given formula.””“
a_n = n + 1
b_n = n*’ (1/3)
return ((1 + b_n / a_n) ** a_n) / (math.e ** b_n)

def first_N_iterates(N):
”"”Generate the first N iterates of f(n).”“"
return [f(n) for n in range(1, N + 1)]

def find_N_epsilon(epsilon):
”””Find the first N_epsilon where |f_n - 11 « epsilon.”””
n = 1
while True:
f_n = f(n)
if abs(f_n - 1) ‹ epsilon:
return n
n += 1

# Input
N = 5
epsilon = 0.1

# Part (a): First N iterates


print(”\nFirst N iterates of f(n):”)
iterates = first_N_iterates(N)
for i, val in enumerate(iterates, start=1):
print(f“f({i}) = {val:.6f}”)

# Part (b): Find N_epsilon


N_epsilon = find_N_epsilon(epsilon)
print(f”\nThe first N_epsilon where |f_n - 1| ‹ {epsilon} is: {N_epsilon}“)

First N iterates of f(n):


f(1) = 0.827729
f(2) = 0.812202
f(3) = 0.810052
f(4) = 0.811561

https://coIab.research.googIe.com/drive/1o7aA1t BIOjD40D8QcP-Kkd22pqqFcI8#scroIITo=9DLTknMMcpEE&printMode=true 4/8


11/26/24, 6:02 PM Lab4.ipynb - Colab
f(5) = 0.814287

The first N_epsilon whene lf_n - 1| < 0.1 is: 95

#Q4

import numpy as np
from scipy.optimize import minimize_scalar

# Define the functions f(x) and g(x)


def f(x):
return 2 * x**2 + 5

def g(x):
return x**2 - 2 * x + 3

# Funct1on to compute f(x) - r_n* g(x)


def objective_function(x, r_n):
return -(f(x) - r_n * g(x)) # Negative for maximization

# Part (a): Compute first N iterates


def f 'te ates(N, x1):
valuN

fon ' n range(N):

r_nalues pend(r_ n'


# Maximize f(x) - r n * g(x) in the interval [1 5]
result = minimize_scalar(objective_function, args=(r_n,), bounds=(1, 5), method='bounded')
nn l’’' # Update x_n
retu 'v eue

# Part (b): Find N_epsilon


def find_N_epsilon(epsilon, x1):
r_n = 0
x_n = x1
n = 1
while True:
r_new = f(x_n) / g(x_n)
if abs(r_new - r_n) ‹ epsilon and n › 1:
break
r_n = r_new
# Maximize f(x) - r_n * g(x) in the interval [1, 5]
result = minimize_scalar(objective_function, args=(r_n,), bounds=(1, 5), method='bounded')
x_n = result.x
n += l
return n

# Input from user


x1 = 2

https://coIab.research.googIe.com/drive/1o7aA1t BIOjD40D8QcP-Kkd22pqqFcI8#scroIITo=9DLTknMMcpEE&printMode=true 5/8


11/26/24, 6:02 PM Lab4.ipynb - Colab
N = 3
epsilon = 0.1

# Part (a): First N iterates


print(”\nFirst N iterates of r(n):”)
r_iterates = first_N_iterates(N, x1)
for i, r in enumerate(r_iterates, start=1):
print(f”r({i}) = {r:.6f}”)

# Part (b): Find N_epsilon


N_epsilon = find_N_epsilon(epsilon, x1)
print(f”\nThe first N_epsilon where |r_n - r_(n-1)| ‹ {epsilon} is: {N_epsilon}”)

First N iterates of r(n):


r(1) = 4.333333
r(2) = 4.350746
r(3) = 4.350781

The first N_epsilon where l°_n - r_(n-1)| < 0.1 is: 2

#Q5

import numpy as np
import matplotlib.pyplot as plt

def power_iteration(A, x0, N):

Perform the power iteration method to approximate the dominant eigenvalue and eigenvector.

Parameters:
A (ndarray): Square matrix of size K x K.
x0 (ndarray): Initial vector of size K (non-zero).
N (int): Number of iterations.

Returns:
xn_list (list of ndarray): List of iterates [x0, xl, ..., xN].
zn_list (list of float): List of z_n values = llf_n+1 - x_nl-I
dominant_eigenvalue (float): Approximation of the dominant eigenvalue.
dominant_eigenvector (ndarray): Approximation of the dominant eigenvector.

xn = x0 / np.linalg.norm(x0) # Normalize initial vector


xn_list = [xn]
zn_list = []

for _ in range(N):
Axn = np.dot(A, xn)
xn_next = Axn / np.linalg.norm(Axn) # Normalize
zn = np.linalg.norm(xn_next - xn) # Difference between successive iterates
zn_list.append(zn)

https://coIab.research.googIe.com/drive/1o7aA1t BIOjD40D8QcP-Kkd22pqqFcI8#scroIITo=9DLTknMMcpEE&printMode=true 6/8


11/26/24, 6:02 PM Lab4.ipynb - Colab
xn = xn_next
xn_list.append(xn)

dominant_eigenvalue = np.linalg.norm(np.dot(A, xn))


dominant_eigenvector = xn
return xn_list, zn_list, dominant_eigenvalue, dominant_eigenvector

# Input

A = np.random.rand(5,5).astype(float)
x0 = np.random.rand(5,1).astype(float)
N = 3

# Run power iteration


xn_list, zn_list, dominant_eigenvalue, dominant_eigenvector = power_iteration(A, x0, N)

# Part (a): Print first N iterates


print(”\nFirst N iterates of x_n:”)
fon i, xn in enumerate(xn_list[:N], start=1):
print(f“x_{i}: {xn}”)

# Part (b): Plot zn vs. n


plt.figure(figsize=(8, 5))
plt.plot(range(1, len(zn_list) + 1), zn_list, marker='o', linestyle='-')
plt.title(“Convergence of I l'_{n+1} - x_nlI (z_n) vs. n”)
plt.xlabel(“n (iteration)”)
plt.ylabel(“z_n = I l'_{n+1} - x_n||”)
plt.grid()
plt.show()

# Part (c): Output dominant eigenvalue and eigenvector


print(f”\nDominant Eigenvalue (Ä): {dominant_eigenvalue:.6f}”)
print(f”Dominant Eigenvector (v): {dominant_eigenvector}”)

https://coIab.research.googIe.com/drive/1o7aA1t BIOjD40D8QcP-Kkd22pqqFcI8#scroIITo=9DLTknMMcpEE&printMode=true 7/8


11/26/24, 6:02 PM Lab4.ipynb - Colab

First N iterates of x n:
x_1: [[0.53908145]
[0.01558963]
[0.67750799]
[0.19754479]
[0.45946397]]
x_2: [[0.35761336]
[0.3467716 ]
[0.55993742]
[0.52713663]
[0.40057359]]
x_3: [[0.38158023]
[0.35198712]
[0.49118525]
[0.58110988]
[0.38929418]]
Convergence of IXX In+1} x n| (z n) vs. n

*':-e=’t-‹-!*’'J’: ::’‹- s’a’"- !:i'!

1.00 1.25 1.30 1.73 2.OD 2.25 2.30 2.75 3.OD


n (iteration)

Dominant Eigenvalue (A): 2.611029


Dominant Eigenvector (v): [[0.37826338]
[0.35121649]
[0.47835652]
[0.59104751]
[0.39421019]]

https://colab.research.google.com/drive/1o7aA1t BIOjD40D8QcP-Kkd22pqqFcI8#scrollTo=9DLTknMMcpEE&printMode=true 8/8


11/26/24, 6:04 PM Lab5.ipynb - Colab

#Q3

import numpy as np

def gram_schmidt_A(u1, u2, u3):


# Define the matrix A
A = np.array([[2, 1, 0],
[1, 3, -1],
[0, -1, 2]])

# Stack the input vectors into a matrix


U = np.column_stack((u1, u2, u3))

# Check if the vectors are linearly independent


if np.linalg.matrix_rank(U) ‹ 3:
print(“The vectors u1, u2, and u3 are not linearly independent.”)
return

# Gram-Schmidt process with custom inner product


def inner_product(x, y):
return np.dot(x.T, np.dot(A, y))

def normalize(v):
return v / np.sqrt(inner_product(v, v))

# v1
v1 = norma11ze(u1)

# v2
proj_u2_v1 = inner_product(u2, v1) / inner_product(v1, v1) * v1
v2 = normalize(u2 - proj_u2_v1)

# v3
proj_u3_v1 = inner_product(u3, v1) / inner_product(v1, vi) * v1
proj_u3_v2 = inner_product(u3, v2) / inner_product(v2, v2) * v2
v3 = normalize(u3 - proj_u3_v1 - proj_u3_v2)

# Output the orthogonal set


print(“The orthogonal set is:”)
print(“v1:“, v1)
print(“v2:“, v2)
print(“v3:“, v3)

# Example Usage
u1 = np.array([1, 0, 0])
u2 = np.array([0, 1, 0])
u3 = np.array([0, 0, 1])

https://coIab.research.googIe.com/drive/1AXBOeb5xAJZIOS6320bn0 FtRBvGUgyY#scroIITo=H-eJUiXHdac2&printMode=true 1/3


11/26/24, 6:04 PM Lab5.ipynb - Colab
gram_schmidt_A(u1, u2, u3)

The orthogonal set is:


v1: [0.70710678 0. 0. ]
v2: [-0.31622777 0.63245553 0. ]
v3: [-0.15811388 0.31622777 0.79056942]

#Q4

import numpy as np

def pagerank(A, tol=1e-6, max_iter=100):

Implements the PageRank algorithm using power iteration.

Parameters:
A (numpy.ndarray): The adjacency matrix (size N x N).
tol (float): Convergence tolerance.
max_iter (int): Maximum number of iterations.

Returns:
v (numpy.ndarray): The principal eigenvector (PageRank scores).

# Normalize the adjacency matrix to get the transition matrix P


P = A / np.sum(A, axis=0, where=(A != 0), keepdims=True)

# Initialize the rank vector v with equal probabilities


N = A.shape[0]
v = np.ones(N) / N

# Power iteration
for i in range(max_iter):
v_new = np.dot(P, v)
v_new /= np.linalg.norm(v_new, 1) # Normalize to keep the sum of ranks 1

# Check for convergence


if np.linalg.norm(v_new - v, 1) ‹ tol:
print(f“Converged in {i+1} iterations.”)
break
v = v_new

return v

# Example Usage
np.random.seed(42)
# Generate a random 10x10 adjacency matrix (e.g., for 10 webpages)
A = np.random.rand(10, 10)

# Apply PageRank
paFerank scores = paFerank(A)
https://coIab.research.googIe.com/drive/1AXBOeb5xAJZIOS6320bn0 FtRBvGUgyY#scroIITo=H-eJUiXHdac2&printMode=true 2/3
11/26/24, 6:04 PM Lab5.ipynb - Colab
print(”PageRank Scores:”, pagerank_scores)

Converged in 8 iterations.
PageRank Scores: [0.1087474 0.08112981 0.08748782 0.11126163 0.08711514 0.1139331
0.09888181 0.1010542 0.12002895 0.09036015]

https://coIab.research.googIe.com/drive/1AXBOeb5xAJZIOS6320bn0 FtRBvGUgyY#scroIITo=H-eJUiXHdac2&printMode=true 3/3


11/26/24, 6:06 PM Lab6.ipynb - Colab

#Q1

import numpy as np

def card_simulation(num_simulations=1000):
# Initialize counters for the conditions
count_at_least_one_ace = 0
count_exactly_two_face_cards = 0

# Define the deck


# 4 Aces, 12 Face Cards (Jack, Queen, King), 36 other cards
deck = ['Ace'] * 4 + ['Face'] * 12 + ['Other'] * 36

# Run the simulation


for _ in range(num_simulations):
# Shuffle the deck and draw 10 cards
shuffled_deck = np.random.permutation(deck)
drawn_cards = shuffled_deck[:10]

# Condition (i): At least one Ace


if 'Ace' in drawn_cards:
count_at_least_one_ace += 1

# Condition (ii): Exactly two face cards


num_face_cards = sum(card == 'Face' for card in drawn_cards)
if num_face_cards == 2:
count_exactly_two_face_cards += 1

# Calculate probabilities
prob_at_least_one_ace = count_at_least_one_ace / num_simulations
prob_exactly_two_face_cards = count_exactly_two_face_cards / num_simulations

# Display results
print(f'Probability of at least one Ace: {prob_at_least_one_ace:.4f}')
print(f'Probability of exactly two face cards: {prob_exactly_two_face_cards:.4f}')

# Run the simulation


card_simulation()

Probability of at least one Ace: 0.6090


Probability of exactly two face cards: 0.3200

#Q2

import random

def birthday_paradox_simulation(trials=10000, group_size=30):


shared_birthday_count = 0

https://coIab.research.googIe.com/drive/1Z3IzMEYIOXncfHwX9wxg8bLjIEHCJQjy#scroIITo=FzC2CTyoeDqt&printMode=true 1/3
11/26/24, 6:06 PM Lab6.ipynb - Colab

for _ in range(trials):
birthdays = [random.randint(1, 36S) for _ in range(group_size)]
if len(birthdays) != len(set(birthdays)): # Check if there's a duplicate
shared_birthday_count += 1

probability = shared_birthday_count / trials


print(f”Probability that at least two people share the same birthday: {probability:.4f}”)

birthday_paradox_simulation()

- Probability that at least two people share the same birthday: 0.703g

#Q3

import random

def ball_simulation(trials=25, draws=5):


colors = ['red', 'blue', 'green']
two_red_count = 0

for _ in range(trials):
bag = random.choices(colors, k=draws) # Randomly draw 5 balls
if bag.count('red') == 2: # Check if there are exactly 2 red balls
two_red_count += 1

average_probability = two_red_count / trials


print(f“Average probability of drawing exactly two red balls: {average_probability:.4f}”)

ball_simulation()

Average probability of drawing exactly two red balls: 0.2400

#Q4

from itertools import permutations


import random

def letter_tile_simulation(trials=100000, draws=6):


tiles = ['A', 'B', 'C', 'D', 'E']
abcde_order_count = 0
aabbcc_any_order_count = 0

for _ in range(trials):
random_draw = random.choices(tiles, k=draws)

# Check for ”ABCDE” in order


if random_draw == ['A', 'B', 'C', 'D', 'E']:
https://coIab.research.googIe.com/drive/1Z3IzMEYIOXncfHwX9wxg8bLjIEHCJQjy#scroIITo=FzC2CTyoeDqt&printMode=true 2/3
11/26/24, 6:06 PM Lab6.ipynb - Colab
abcde_order_count += 1

# Check for ”AABBCC” in any order


if sorted(random_draw) == sorted(['A', 'A', 'B', 'B', 'C', 'C']):
aabbcc_any_order_count += 1

prob_abcde = abcde_order_count / trials


prob_aabbcc = aabbcc_any_order_count / trials

print(f“Probability of forming the word 'ABCDE' in order: {prob_abcde:.6f}“)


print(f“Probability of forming the word 'AABBCC' in any order: {prob_aabbcc:.6f}”)

letter_tile_simulation()

Probability of forming the word 'ABCDE' in order: 0.000000


Probability of forming the word 'AABBCC' in any order: 0.006030

https://coIab.research.googIe.com/drive/1Z3IzMEYIOXncfHwX9wxg8bLjIEHCJQjy#scroIITo=FzC2CTyoeDqt&printMode=true 3/3

You might also like