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)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值