一、利用numpy庫,創建兩個數組A、B,兩個數組的shape均為4*5,數組A的元素為
,數組B的元素為
。編程實現以下功能:
1)輸出A+B 、B-A、A*B、A/B的結果;
2)對數組A的中間兩行的元素進行求和,並輸出。
import numpy as np arrayA = np.array([[0,1,2,3,4], [5,6,7,8,9], [10,11,12,13,14], [15,16,17,18,19]]) arrayB = np.array([[100,101,102,103,104], [105,106,107,108,109], [110,111,112,113,114], [115,116,117,118,119]]) print(arrayA + arrayB) print(arrayA * arrayB) print(arrayB - arrayA) print(arrayA / arrayB) print(sum(arrayA[1,:])+sum(arrayA[2,:]))
二、“雞兔同籠”問題:今有雞兔同籠,上有三十五頭,下有九十四足。問雞兔各多少?,請利用numpy庫的linalg模塊編程實現。
import numpy as np heads , foots = 35, 94 A = np.array([[1,1],[2,4]]) #方程組的系數 B = np.array([heads,foots]) #方程組右側的常數矩陣 X = np.linalg.solve(A,B) print(X) print("雞為:{}只, 兔為: {}只".format(X[0],X[1]))
三、參考教材閱讀並運行“阻尼衰減曲線坐標圖”繪制代碼,理解編寫科學坐標系的方法,繪制如下圖所示阻尼衰減曲線圖:
import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.rcParams['font.family']='SimHei' matplotlib.rcParams['font.sans-serif']=['SimHei'] def Draw(pcolor, nt_point,nt_text,nt_size): plt.plot(x,y,'k',label="$exp_decay$",color=pcolor,linewidth=3,linestyle="-") plt.plot(x,z,"b--",label="$cos(x^2)$",linewidth=1) plt.xlabel('時間(s)') plt.ylabel('幅度(mV)') plt.title('阻尼衰減曲線繪制') plt.annotate('$\cos(2 \pi t) \exp(-t)$',xy=nt_point, xytext=nt_text,fontsize=nt_size,arrowprops=dict(arrowstyle='->',connectionstyle="arc3,rad=.1")) def Shadow(a,b): ix = (x>a) & (x<b) plt.fill_between(x,y,0,where=ix,facecolor='grey',alpha=0.25) plt.text(0.5 * (a + b),0.2,r"$\int_a^b f(x)\mathrm{d}x$",horizontalalignment='center') def XY_Axis(x_start,x_end,y_start,y_end): plt.xlim(x_start,x_end) plt.ylim(y_start,y_end) plt.xticks([np.pi/3,2*np.pi/3,1*np.pi,4*np.pi/3,5*np.pi/3],['$\pi/3$','$2\pi/3$','$\pi$','$4\pi/3$','$5\pi/3$']) x=np.linspace(0.0,6.0,100) y=np.cos(2*np.pi*x)*np.exp(-x)+0.8 z=0.5*np.cos(x**2)+0.8 note_point,note_text,note_size=(1,np.cos(2*np.pi)*np.exp(-1)+0.8),(1,1.4),14 fig=plt.figure(figsize=(8,6),facecolor="white") plt.subplot(111) Draw("red",note_point,note_text,note_size) XY_Axis(0,5,0,1.8) Shadow(0.8,3) plt.legend() plt.savefig('sample.JPG') plt.show()