欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python-Scipy(第十四周作业)

程序员文章站 2022-07-01 18:26:26
...

Exercise 10.1: Least squares

题目要求

给出矩阵A,向量b,用最小二乘法求x,并求出残差的模
代码:

import scipy
import scipy.spatial

m = 8
n = 7
A = scipy.random.rand(m, n) * scipy.random.randint(1, 10)
b = scipy.random.rand(m) * scipy.random.randint(1, 10)
x, resid, rnk, s = scipy.linalg.lstsq(A, b)
print('A :\n', A)
print('b :\n', b)
print('x :\n', x)
print('Norm of residual : ', resid / n)

结果:
Python-Scipy(第十四周作业)

Exercise 10.2: Optimization

题目要求

求给出函数f(x)=(sin(x2))2ex2的最大值
代码:

import scipy
import math
import scipy.optimize as opt

func = lambda x: (math.sin(x - 2) ** 2) * math.exp(-x * x)
maximum = opt.fmin(lambda x: -func(x), 1, full_output=True, disp=False)
print('max point is', maximum[0], ',value is', -maximum[1])
print('iterations is', maximum[2], ',function evaluations is', maximum[3])

结果:
Python-Scipy(第十四周作业)

Exercise 10.3: Pairwise distances

题目要求

计算N个点中每两个点间的距离,这里取4个点
代码:

import scipy
import math
import scipy.spatial
import scipy.optimize as opt

m, n = 2, 4
X = scipy.random.rand(n, m) * scipy.random.randint(1, 10)
Y = scipy.spatial.distance.pdist(X)
print('points:\n', X)
print('distance:', Y)

结果:
Python-Scipy(第十四周作业)