注:本文为国科大《Python 科学计算与数据处理》课程 Numpy 作业的代码,仅供学习参考,如有错误欢迎指出。
题目1
以四种方式运行三角波(triangle_wave)函数,比较各方式的运行速度与计算结果。
import numpy as np
import time
def triangle_wave(x, c, c0, hc):
x = x - int(x)
if x >= c:
r = 0.0
elif x < c0:
r = x / c0 * hc
else:
r = (c-x) / (c-c0) * hc
return r
def method1(x):
y = np.array([triangle_wave(t, 0.6, 0.4, 1.0) for t in x])
return y
def method2(x):
triangle_ufunc1 = np.frompyfunc(triangle_wave, 4, 1)
y = triangle_ufunc1(x, 0.6, 0.4, 1.0)
return y
def method3(x):
triangle_ufunc2 = np.frompyfunc(lambda x: triangle_wave(x, 0.6, 0.4, 1.0), 1, 1)
y = triangle_ufunc2(x)
return y
def method4(x):
triangle_ufunc3 = np.vectorize(triangle_wave, otypes=[float]) # numpy 1.24 不再支持 np.float,直接用 float
y = triangle_ufunc3(x, 0.6, 0.4, 1.0)
return y
if __name__ == '__main__':
x = np.linspace(0, 2, 1000)
funcs = [method1, method2, method3, method4]
# 计时,运行10次取平均
for i, func in enumerate(funcs):
start_time = time.time()
for j in range(10):
func(x)
end_time = time.time()
print('time{}: {} s'.format(i+1, (end_time-start_time)/10))
# 比较运算结果
isEqual = True
for i in range(len(funcs)-1):
if (funcs[i](x) == funcs[i+1](x)).all():
print('y{} 和 y{} 相等'.format(i+1, i+2))
else:
print('y{} 和 y{} 不相等'.format(i + 1, i + 2))
isEqual = False
if isEqual:
print('所有方法运算结果相同')
题目2
arr = 5 - np.arange(1, 13).reshape(4, 3)
1)计算所有元素及每一列的和;
2)计算每一个元素、每一列的累积和;
3)计算每一行的累计积;
4)计算所有元素的最小值;
5)计算每一列的最大值;
6)计算所有元素、每一行的均值;
7)计算所有元素、每一列的中位数;
8)计算所有元素的方差,每一行的标准差。
import numpy as np
arr = 5 - np.arange(1,13).reshape(4,3)
# 所有元素求和
a = np.sum(arr)
# 每列求和
a = np.sum(arr, axis=0)
# 元素累计和
a = np.cumsum(arr)
# 列累计和
a = np.cumsum(arr, axis=0)
# 行累计积
a = np.cumprod(arr, axis=1)
# 所有元素的最小值
a = np.min(arr)
# 每列最大值
a = np.max(arr, axis=0)
# 所有元素均值
a = np.mean(arr)
# 每行均值
a = np.mean(arr, axis=1)
# 所有元素中位数
a = np.median(arr)
# 每列中位数
a = np.median(arr, axis=0)
# 所有元素方差
a = np.var(arr)
# 每行标准差
a = np.std(arr, axis=1)
题目3
在数组
[1, 2, 3, 4, 5]
中相邻数字之间插入两个0。
import numpy as np
# 方法一
Z = np.array([1,2,3,4,5])
i = 1
while i < len(Z):
Z = np.insert(Z, i, [0, 0])
i += 3
# 方法二
Z0 = np.array([1,2,3,4,5])
gap = 2
Z1 = np.zeros(len(Z0) + (len(Z0)-1) * (gap))
Z1[::nz+1] = Z0
题目4
试对
Z = np.random.random((5,5))
进行归一化,即将所有元素等比缩放到0-1范围。
import numpy as np
Z = np.random.random((5,5))
Zmax = np.max(Z)
Zmin = np.min(Z)
Z = (Z - Zmin)/(Zmax - Zmin)
题目5
找出数组中与给定值最接近的数。
例:Z=array([[0,1,2,3],[4,5,6,7]])
,目标值z=5.1
,Z中最接近的数为5。
import numpy as np
Z = np.array([[0,1,2,3],[4,5,6,7]])
target = 5.1
X = abs(Z - target) # 绝对差值
idx = np.argmin(X) # 最接近元素的下标
ans = Z.flatten()[idx]
题目6
解方程组:
{ 3 x + 6 y − 5 z = 12 x − 3 y + 2 z = − 2 5 x − y + 4 z = 10 \begin{cases} 3x + 6y - 5z = 12\\ x - 3y + 2z = -2\\ 5x - y + 4z = 10 \end{cases} ⎩ ⎨ ⎧3x+6y−5z=12x−3y+2z=−25x−y+4z=10
import numpy as np
A = np.array([[3, 6, -5], [1, -3, 2], [5, -1, 4]])
B = np.array([12, -2, 10])
ans = np.linalg.solve(A, B)
题目7
g ( x ) = s i n ( z 2 ) + s i n 2 ( z ) g(x) = sin(z^2) + sin^2(z) g(x)=sin(z2)+sin2(z),其中 z = 5 ( x − 1 ) z = 5(x - 1) z=5(x−1)
对 g ( y ) g(y) g(y) 在100个切比雪夫节点之上分別使用 Polynomial 和 Chebyshev 进行插值,在 [-1,1] 区间上取1000个等距点对误差进行比较。
import numpy as np
from numpy.polynomial import Chebyshev, Polynomial
def f(x):
z = (x - 1) * 5
return np.sin(z**2) + np.sin(z)**2
n = 100
x = Chebyshev.basis(n).roots() # 100个切比雪夫节点
y1 = Chebyshev.fit(x, f(x), n - 1, domain=[-1, 1])
y2 = Polynomial.fit(x, f(x), n - 1, domain=[-1, 1])
xd = np.linspace(-1, 1, 1000) # 1000个等距点
print("Chebyshev Fit 最大误差:", abs(y1(xd) - f(xd)).max())
print("Polynomial Fit 最大误差:", abs(y2(xd) - f(xd)).max())
题目8
用 np.bincount 函数统计青少年年龄和身高
import numpy as np
f = np.loadtxt("height.csv", delimiter=",")
ages = np.floor(f[:,0]).astype(int) # 年龄取整
heights = f[:,1]
min_age = np.min(ages)
cnts = np.bincount(ages)[min_age:] # 各年龄段人数
sums = np.bincount(ages, heights)[min_age:] # 各年龄段身高分别求和
ans = sums/cnts # 各年龄段平均身高
题目9
使用二项分布进行计算:同时抛5枚硬币,如果正面朝上少于3枚,则输掉8元,否则就赢8元。如果手中最初有1000元,请问抛掷10000次后会是什么情况?
import numpy as np
import matplotlib.pyplot as plt
cnt = 10000
money = np.zeros(cnt)
money[0] = 1000
result = np.random.binomial(5, 0.5, size=cnt)
for i in range(1, cnt):
money[i] = money[i-1]-8 if result[i] < 3 else money[i-1]+8
print("left money:", money[-1])
plt.plot(np.arange(cnt), money)
plt.show()