高级编程作业第十一次作业

本文通过三个实例介绍了使用Python进行数值计算的方法:最小二乘法解决欠定方程组问题;利用优化算法寻找特定函数的最大值;并展示了如何计算点对之间的距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Exercise 10.1: Least squares

Generate matrix A ∈ Rm×n with m > n. Also generate some vector b ∈ Rm.

Now find x = arg minx ||Ax − b||2.

Print the norm of the residual

用numpy里的random的rand和mat生成矩阵,最后用最小二乘法和乘法函数dot和取逆函数inv算出x。

from numpy import *
from scipy.linalg import *
from scipy.stats import *
import math
m,n=0,1
while(n>m):
    m=int(input("Input m "))
    n=int(input("Input n "))
    if(n>m):
        print("Invalid input,input m,n again")
A=mat(random.rand(m,n))
b=mat(random.rand(m,1))
x=dot(dot(inv(dot(A.T,A)),A.T),b)
print(x)

Exercise 10.2: Optimization

Find the maximum of the function

            f(x) = sin^2(x − 2)e^(−x^2)

由于只知道最小值的函数,要先对函数取反,再用scipy.optimize里的fmin找到最小值对应的x值,最后把x对应的函数值求出来再取反就是答案。

from numpy import *
from scipy.linalg import *
import scipy.optimize as opt
from scipy.stats import *
import math
def liangjan(x):
    return -((math.sin(x-2)**2)*math.exp(-(x**2)))
x=opt.fmin(liangjan,1)
print("Maximum is : ",liangjan(x)*-1)

最后算出来的最大值是 0.9116854101234255

Exercise 10.3: Pairwise distances

Let X be a matrix with n rows and m columns. How can you compute the pairwise distances betweenevery two rows?As an example application, consider n cities, and we are given their coordinates in two columns. Nowwe want a nice table that tells us for each two cities, how far they are apart.

Again, make sure you make use of Scipy’s functionality instead of writing your own routine.

用scipy.spatial.distance里的pdist算距离,再用squareform转成矩阵形式的距离打印出来。

from numpy import *
from scipy.linalg import *
from scipy.spatial.distance import *
from scipy.stats import *
import math
m=int(input("Input m "))
n=int(input("Input n "))
X=mat(random.rand(m,n))
cities=pdist(X)
ans=squareform(cities)
print(ans)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值