RS Exercize1 4

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

#Ex1

#a
def fibonacci_recursive(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)

#b
# For F(19)
result_19 = fibonacci_recursive(19)
print(f"F(19) = {result_19}")

# for F(38)
result_38 = fibonacci_recursive(38)
print(f"F(38) = {result_38}")

#c
def fibonacci_iterative(n):
if n == 0:
return 0
elif n == 1:
return 1

prev, current = 0, 1
for _ in range(2, n + 1):
prev, current = current, prev + current

return current

result_iterative_19 = fibonacci_iterative(19)
print(f"F(19) = {result_iterative_19}")

result_iterative_38 = fibonacci_iterative(38)
print(f"F(38) = {result_iterative_38}")

#ex2
import numpy as np

def fibonacci_matrix(n):
A = np.array([[1, 1], [1, 0]])
result_matrix = np.linalg.matrix_power(A, n)
return result_matrix[0, 0]

# Testing the function for n = 101


result_101 = fibonacci_matrix(101)
print(f"F(101) = {result_101}")
#When you run fibonacci_matrix(101), you might observe a large integer as the
output.
#This is because the Fibonacci numbers grow exponentially,
#and computing them using matrix exponentiation can result in very large
numbers.
#The exact value of F(101) is a 21-digit number.
#This approach using matrices is more efficient than the naive recursive
approach for large values of n.

#ex3
#a
import numpy as np

matrix_a = np.ones((3, 3))


print("Matrix A:\n", matrix_a)

#b
matrix_b = np.eye(3)
print("Matrix B:\n", matrix_b)

#c
result_c = matrix_a + matrix_b
print("Result of addition (A + B):\n", result_c)

#d
vector = np.array([7, 11, 2022])
result_d = np.dot(matrix_b, vector)
print("Result of multiplication (B * vector):\n", result_d)

#e
matrix_e = np.array([[1, 0, 4, 4],
[0, 1, 4, 4],
[0, 0, 19, 0],
[0, 0, 0, 2]])

print("Matrix E:\n", matrix_e)

#ex4
#a
import numpy as np

def monteCarloPi(N):
points_inside_circle = 0

for _ in range(N):
x, y = np.random.uniform(-1, 1, 2)
if x**2 + y**2 <= 1:
points_inside_circle += 1

pi_approx = 4 * (points_inside_circle / N)
return pi_approx

#b
def monteCarloSphere(N, d):
points_inside_sphere = 0

for _ in range(N):
point = np.random.uniform(-1, 1, d)
if np.linalg.norm(point) <= 1:
points_inside_sphere += 1

volume_approx = (2**d) * (points_inside_sphere / N)


return volume_approx

dimensions = [3, 4, 10, 100, 300]


N = 10000

for d in dimensions:
volume_approx = monteCarloSphere(N, d)
print(f"Dimension {d}: Approximated Volume = {volume_approx}")

You might also like