Lab_Changed
Lab_Changed
ipynb - Colab
#Q1
import numpy as np
import random as rand
low = -10
high = 10
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)
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)
#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)
#Q5
import numpy as np
import matplotlib.pyplot as plt
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 -
#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]]
#Q2
import numpy as np
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])
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]
main ( )
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')
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
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)
if enamel == “ main ”:
main(2)
#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)
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()
if enamel == “ main “:
main()
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 -
#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
#Q4
import numpy as np
from scipy.optimize import minimize_scalar
def g(x):
return x**2 - 2 * x + 3
#Q5
import numpy as np
import matplotlib.pyplot as plt
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.
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)
# Input
A = np.random.rand(5,5).astype(float)
x0 = np.random.rand(5,1).astype(float)
N = 3
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
#Q3
import numpy as np
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)
# Example Usage
u1 = np.array([1, 0, 0])
u2 = np.array([0, 1, 0])
u3 = np.array([0, 0, 1])
#Q4
import numpy as np
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).
# 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
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]
#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
# 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}')
#Q2
import random
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
birthday_paradox_simulation()
- Probability that at least two people share the same birthday: 0.703g
#Q3
import random
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
ball_simulation()
#Q4
for _ in range(trials):
random_draw = random.choices(tiles, k=draws)
letter_tile_simulation()
https://coIab.research.googIe.com/drive/1Z3IzMEYIOXncfHwX9wxg8bLjIEHCJQjy#scroIITo=FzC2CTyoeDqt&printMode=true 3/3