本次作业是如下三题:
10.1:代码如下:
import numpy as np
import scipy.optimize
def solve_1(m,n):
A = np.random.randn(m, n)
b = np.random.randn(m)
x = scipy.optimize.lsq_linear(A, b)
print(x.fun) #fun 项为残差矩阵
print( np.linalg.norm(x.fun,ord = 2))
solve_1(10,5)#这里随便设 m = 10 , n = 5
运行结果如图:
10.2
import numpy as np
import scipy.optimize
def solve_2():
y = lambda x: -np.sin(x - 2) * np.sin(x - 2) * np.exp(-(x * x))
max_x = scipy.optimize.fmin(func = y, x0 = 0)
print(-y(max_x))
#没有找到直接求最大值的函数,所以求负数的最小值然后再取相反数
solve_2()
运行结果如下:
10.3
代码如下:
import numpy as np
import scipy.optimize
import scipy.spatial.distance as ds
def solve_3(n,m):
A = np.random.rand(n, m)
ori_solution = ds.pdist(A)#计算出原始距离
matrix_solution = ds.squareform(ori_solution)#把距离换成与矩阵一一对应的形式
print(matrix_solution)
solve_3(n = 5, m = 5)#这里随便设n = 5 m = 5
运行结果如下: