5章ではNumpyやScipyを本格的に使っていく。
[:contents] 練習問題5-1から5-3
参照渡し、浅いコピーと深いコピーについては、こちらを参照
練習問題5-1から5-3
import numpy.random as random #練習問題 sample_names = np.array(['a', 'b', 'c', 'd', 'e']) random.seed(0) data = random.randn(5, 5) #sample_nameのbに該当する部分を抽出 data[sample_names=='b'] #sample_nameのc以外に該当する部分を抽出 data[sample_names!='c'] #print(data) x = np.array([1, 2, 3, 4, 5]) y = np.array([6, 7, 8, 9, 10]) a = ['fuga','fuga', 'hoge', 'hoge', 'fuga'] print(np.where(a=='fuga', x, y))
練習問題5-4
- 配列についてすべての要素の平方根を計算
- 配列の最大値、最小値、合計値、平均値を計算
- 対角成分の和を計算
sample_multi_array_data2 = np.arange(16).reshape(4, 4) print(np.exp(sample_multi_array_data2)) print(sample_multi_array_data2.min(), sample_multi_array_data2.max(), sample_multi_array_data2.sum(), sample_multi_array_data2.mean()) print(np.diag(sample_multi_array_data2))
ブロードキャストの説明はこちらを参照
演習問題5-7
配列を縦に結合
演習問題5-8
配列を横に結合
演習問題5-9
リストの各要素に3を加える
sample_array1 = np.arange(12).reshape(3, 4) sample_array2 = np.arange(12).reshape(3, 4) #縦に結合 np.concatenate([sample_array1, sample_array2], axis=0) np.vstack((sample_array1, sample_array2)) #横に結合 np.concatenate([sample_array1, sample_array2], axis=1) np.hstack((sample_array1, sample_array2)) sample_list = np.array([1, 2, 3, 4, 5]) print(sample_array + 3)
練習問題5-10, 11, 12
以下のデータについて、線形補間、2次のスプライン補間、3次のスプライン補間を行い、グラフを図示せよ。
x = np.linspace(0, 10, num=11, endpoint=True) y = np.sin(x**2/5.0) plt.plot(x, y, 'o') plt.grid(True)
練習問題5-10から5-12
from scipy import interpolate x = np.linspace(0, 10, num=11, endpoint=True) y = np.sin(x**2/5.0) plt.plot(x, y, 'o') plt.grid(True) f = interpolate.interp1d(x, y, 'linear') plt.subplot(1, 3, 1) plt.plot(x, f(x), '-') xnew = np.linspace(0, 10, num=30, endpoint=True) #スプライン2次補間を追加 f2 = interpolate.interp1d(x, y, 'quadratic') plt.subplot(1, 3, 2) plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--') #スプライン3次補間を追加 f3 = interpolate.interp1d(x, y, 'cubic') plt.subplot(1, 3, 3) plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--', xnew, f3(xnew), 'x')P
特異値分解
import scipy as sp #特異値分解 A = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) U, s, Vs = sp.linalg.svd(A) #print(U) #print(s) #print(Vs) m, n = A.shape S = sp.linalg.diagsvd(s,m,n) print('U.S.V = \n', U@S@Vs)
LU分解とコレスキー分解は数値計算を勉強する際に
scipy integrateのドキュメント
Todo ローレンツ方程式
練習問題5-15、5-16
[tex: \int^{2}_{0} (x+1)2 dx]の値を求めよ
の値を求めよ