高级编程技术 scipy课后习题

步骤如下:

(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"))


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值