scipy练习

本文通过三个练习案例介绍了Scipy库的应用:最小二乘法求解矩阵方程、使用优化方法寻找函数最大值以及计算矩阵中行间的两两距离。这些案例涵盖了科学计算中的常见任务,演示了如何利用Scipy高效解决实际问题。

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

scipy练习


10.1

Exercise 10.1: Least squares Generate matrix A ∈ Rm×n with m > n.
Also generate some vector b ∈ Rm.
Now find x = argminxkAx−bk2.
Print the norm of the residual.

from scipy.linalg import toeplitz
from scipy.optimize import minimize
from scipy.spatial.distance import *
import numpy as np 
import scipy.stats
m = 20
n = 10
#----------------------------------------
#question 1
#----------------------------------------

A = np.random.random(size = (m,n))
b = np.random.random(size = (m,1))
print(A)
print(b)
x = np.array(np.linalg.lstsq(A,b,rcond = -1)[0])
print(x)

10.2

Exercise 10.2: Optimization Find the maximum of the function
f(x) = sin2(x−2)e−x2


from scipy.linalg import toeplitz
from scipy.optimize import minimize
from scipy.spatial.distance import *
import numpy as np 
import scipy.stats
m = 20
n = 10
#----------------------------------------
#question 2
#----------------------------------------
def ex(x):
    return (-1)*np.sin(x-2)**2*np.exp((0-1)*x**2)        #求最大值 利用minimize 加负号

print((-1)*minimize(ex,0).fun)

10.3

Exercise 10.3: Pairwise distances Let X be a matrix with n rows and m columns. How can you compute the pairwise distances between every two rows?
As an example application, consider n cities, and we are given their coordinates in two columns. Now we 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.

from scipy.linalg import toeplitz
from scipy.optimize import minimize
from scipy.spatial.distance import *
import numpy as np 
import scipy.stats
m = 20
n = 10
#----------------------------------------
#question 3
#----------------------------------------

x = np.random.random(size = (n,m))
print(pdist(x))

m = np.random.random(size = (n,2))
print(pdist(m))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值