numpy练习

Numpy练习


9.1

Calculate A + A, AA>,A>A and AB. Write a function that computes A(B−λI) for any λ.

import numpy as np 
from scipy.linalg import toeplitz

A = np.random.normal(size=(200,500))
B = toeplitz(np.random.random((500,1)),np.random.random((500,1)))
# A + A
X1 = A + A
# AAT
X2 = np.dot(A,A.T)
# ATA
X3 = np.dot(A.T,A)
# AB
X4 = np.dot(A,B)
def cal(i):
    m = i * np.identity(500)
    m = B - m
    return np.dot(A,m)

9.2

Generate a vector b with m entries and solve Bx = b.

b = np.random.random(size = (500,1))
x = np.linalg.solve(B,b)

9.3

Compute the Frobenius norm of A: kAkF and the infinity norm of B: kBk∞. Also find the largest and smallest singular values of B.

Af = np.linalg.norm(A,ord = 'fro')
Bi = np.linalg.norm(B,np.inf)
m,n = np.linalg.eig(B)
B_max = max(m)
B_min = min(m)

9.4

Generate a matrix Z, n × n, with Gaussian entries, and use the power iteration to find the largest eigenvalue and corresponding eigenvector of Z. How many iterations are needed till convergence?
Optional: use the time.clock() method to compare computation time when varying n.

Z = np.random.normal((200,200))
n = np.ones((200,1))
def power_convergence(Z, n, e=1e-6, N=1e8):
    c = 1
    y = n/n[np.argmax(np.abs(n))]
    x = np.dot(Z, n)
    b = x[np.argmax(np.abs(x))]
    if (np.abs(x/b - y) < e).all():
        t = b
        return (t, y, c)
    while (np.abs(x/b - y) > e).any() and c < N:
        c = c+1
        m = x[np.argmax(np.abs(x))]
        y = x/m
        x = Z.dot(y)
        b = x[np.argmax(np.abs(x))]
    return (b, y, c)
answer = power_convergence(Z,n)
print(answer[0])
print(answer[1])
print(answer[2])

迭代次数依赖于特征根

9.5

Generate an n×n matrix, denoted by C, where each entry is 1 with probability p and 0 otherwise. Use the linear algebra library of Scipy to compute the singular values of C. What can you say about the relationship between n, p and the largest singular value?

p = 0.3
C = np.where(np.random.random((200,200)) < p,1,0)
u,s,v = scipy.linalg.svd(c)
print(n*p)
print(max(s))

n*p和max(s)的值接近

9.6

Write a function that takes a value z and an array A and finds the element in A that is closest to z. The function should return the closest value, not index.
Hint: Use the built-in functionality of Numpy rather than writing code to find this value manually. In particular, use brackets and argmin.

def findne(A,z):
    a,a = A.shape()
    A1 = np.abs(A-z)
    i = np.argmin(A1)
    print(A[i//200][i%200])
    return A[i//200][i%200]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值