Python编程作业【第十三周】(scipy homework)

Scipy


Exercise 10.1: Least squares

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

def func(x):
    return -1 * math.pow(math.sin(x - 2), 2) * math.pow(math.e, -1.0 * x * x)
def find_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)

你可能感兴趣的:(Python作业)