步骤如下:
(1)m = int(input(" Please input m: "))
n = int(input(" Please input n: "))
if m < n:
m, n = n, m
因为题目没有要求m和n的具体值,只要求m的值大于n的值,所以通过用户交互来确定m和n的值。
(2)A = np.matrix(np.random.rand(m, n))
b = np.matrix(np.random.rand(m, 1))
因为题目没有要求矩阵A和b的分布,所以使用随机数中的均匀分布。
(3)x, residuals, rank, s = scipy.linalg.lstsq(A, b)
norm = scipy.linalg.norm(b - np.dot(A, x), ord = 2)
分别使用 scipy.linalg 中的 lstsq 和 norm 计算最小二乘和残差。
(4)print("\n x is \n", x)
print("\n norm is ", norm)
输出结果。
运行样例如下:
完整代码如下:
# Exercise 10.1
import numpy as np
import scipy.linalg
m = int(input(" Please input m: "))
n = int(input(" Please input n: "))
if m < n:
m, n = n, m
A = np.matrix(np.random.rand(m, n))
b = np.matrix(np.random.rand(m, 1))
x, residuals, rank, s = scipy.linalg.lstsq(A, b)
norm = scipy.linalg.norm(b - np.dot(A, x), ord = 2)
print("\n x is \n", x)
print("\n norm is ", norm)
步骤如下:
(1) def fun(x):
return(-(math.sin(x-2)**2)*math.exp(-(x**2)))
定义函数,其中fun(x) = - f(x)
(2) fval = -scipy.optimize.brute(fun, ((-10, 10, 0.1),),full_output=True)[1]
因为我没找到使用scipy.optimize.brute求最大值的方法,所以退而求其次先将函数反过来求最小值,在将最小值取反就是最大值。
(3)print("\n The maximum is : ", fval)
输出结果
运行样例如下:
完整代码如下:
# Exercise 10.2
import numpy as np
import math
import scipy.optimize
def fun(x):
return(-(math.sin(x-2)**2)*math.exp(-(x**2)))
fval = -scipy.optimize.brute(fun, ((-10, 10, 0.1),),full_output=True)[1]
print("\n The maximum is : ", fval)
步骤如下:
(1)n = int(input(" Please input the row of matrix: "))
m = int(input(" Please input the column of matrix: "))
通过用户交互确定矩阵的行和列
(2)X = np.matrix(np.random.rand(n, m))
用均匀分布的随机数生成n行m列的矩阵
(3)print("\n The matrix X is: \n", X)
输入矩阵X
(4)print("\n The pairwise distances between every two rows are: \n", scipy.spatial.distance.cdist(X, X, "euclidean"))
scipy.spatial.distance.cdist(XA, XB, metric='euclidean', p=None, V=None, VI=None, w=None),该函数用于计算两个输入集合的距离,通过metric参数指定计算距离的不同方式得到不同的距离度量值,其中的metric='euclidean'参数指定了欧式距离,也就是我们平常说的距离。
运行样例如下:
完整代码如下:
# Exercise 10.3
import numpy as np
import scipy.spatial.distance
n = int(input(" Please input the row of matrix: "))
m = int(input(" Please input the column of matrix: "))
X = np.matrix(np.random.rand(n, m))
print("\n The matrix X is: \n", X)
print("\n The pairwise distances between every two rows are: \n", scipy.spatial.distance.cdist(X, X, "euclidean"))