import numpy as np
from scipy import linalg
import matplotlib.pyplot as plt
import math
m = 201
n = 200
A = np.random.randint(1, 10, (m, n))
b = np.random.randint(1000, 2000, (m, 1))
x_hat = np.linalg.lstsq(A, b, rcond=None)[0]
# x = linalg.solve(A, b)
err = np.dot(A, x_hat) - b
err_norm = np.linalg.norm(err, ord = 2)
print(err)
print(err_norm)
Exercise 10.2: Optimization
import math
from scipy import optimize
deffunc(x):return -1 * math.pow(math.sin(x - 2), 2) * math.pow(math.e, -1.0 * x * x)
deffind_max(func, x):return -func(x)
a = optimize.minimize_scalar(func)
print("x of maximum value: ", str(a.x))
print("maximum value: ", str(-1 * func(a.x)))
Exercise 10.3: Pairwise distances
import numpy as np
from scipy import linalg
import matplotlib.pyplot as plt
import math
n = 5
m = 2
A = np.random.randint(1, 10, (n, m))
res = np.zeros((n, n))
print(res)
for i in range(0, n):
for j in range(0, n):
distance_vec = A[i] - A[j]
distance = math.sqrt(math.pow(distance_vec[0], 2) + math.pow(distance_vec[1], 2))
res[i, j] = distance
print(A)
print(res)