Numpy习题

元素生成:

import numpy as np
from scipy.linalg import toeplitz
import time
mu,sigma = 0, 1.0
n,m = 200, 500
A = np.random.normal(loc = mu, scale = sigma, size = (n,m))

C = [a for a in range(1, m + 1)]
B = toeplitz(C,C)

9.1

print(A + A)

print(np.dot(A, A.T))

print(np.dot(A.T, A))

print(np.dot(A, B))

C = B - lamda * (np.eye(m))
print(np.dot(A, C))

9.2

b = np.ones((m, 1))
x = np.linalg.solve(B, b)
print(x)

9.3

A_F = np.linalg.norm(A, 'fro')
print("the Frobenius norm:", A_F)

B_F = np.linalg.norm(B, np.inf)
print("the infinity norm:", B_F)

lar_sin = np.linalg.norm(B, 2)
smal_sin = np.linalg.norm(B, -2)
print("the largest singular:", lar_sin)
print("the smallest singular:", smal_sin)

9.4

Z = np.random.standard_normal((n, n))
num = 0
u_k = np.ones(n)
v_k_norm = 0
v_k = np.zeros(n)

begin = time.clock()
while (True):
    v_k = np.dot(Z, u_k)
    v_k_norm_temp = v_k_norm
    v_k_norm = np.linalg.norm(v_k)
    u_k = v_k / v_k_norm
    num += 1
    if (abs(v_k_norm_temp - v_k_norm) < 0.0005):
        break;
end = time.clock()

print("the largest eigenvalue:", v_k_norm)
print("the corresponding eigenvector:", u_k)
print("The number of iterations:", num)
print("computation time when varying n:", end - begin)

9.5

p = 0.5
C = np.random.binomial(1, p, (n, n))

lar_sin = np.linalg.norm(C, 2)
smal_sin = np.linalg.norm(C, -2)
print("the smallest singular:", smal_sin)
print("the largest singular:", lar_sin)

print("n * p:", n * p)
print("the largest singular is closed with n * p \nso that we can say they are equal!")

9.6

def fun_closest(A, z):
    B, C = A[A > z], A[A <= z]
    ceil, floor = 0, 0

    if (len(B)):
        ceil = np.argmin(B)
    else:
        return C[np.argmax(C)]

    if (len(C)):
        floor = np.argmax(C)
    else:
        return B[ceil]

    if (abs(B[ceil] - z) < abs(C[floor] - z)):
        return B[ceil]
    else:
        return C[floor]

z = -5
closest = fun_closest(A, z)
print("the closest value:", closest)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值