Python求陰影部分面積
一、前言說明
今天看到微信群裡一道六年級數學題,如下圖,求陰影部分面積
看起來似乎並不是很難,可是博主新增各種輔助線,寫各種方法都沒出來,不得已而改用寫Python程式碼來求面積了
二、思路介紹
1.用Python將上圖畫在座標軸上,主要是斜線函式和半圓函式
2.均勻的在長方形上面灑滿豆子(假設是豆子),求陰影部分豆子佔比*總面積
三、原始碼設計
1.做圖原始碼
1 import matplotlib.pyplot as plt 2 import numpy as np 3 4 5 def init(): 6plt.xlabel('X') 7plt.ylabel('Y') 8 9fig = plt.gcf() 10fig.set_facecolor('lightyellow') 11fig.set_edgecolor("black") 12 13ax = plt.gca() 14ax.patch.set_facecolor("lightgray")# 設定ax區域背景顏色 15ax.patch.set_alpha(0.1)# 設定ax區域背景顏色透明度 16ax.spines['right'].set_color('none') 17ax.spines['top'].set_color('none') 18ax.xaxis.set_ticks_position('bottom') 19ax.yaxis.set_ticks_position('left') 20ax.spines['bottom'].set_position(('data', 0)) 21ax.spines['left'].set_position(('data', 0)) 22 23 24 # 原下半函式 25 def f1(px, r, a, b): 26return b - np.sqrt(r**2 - (px - a)**2) 27 28 29 # 斜線函式 30 def f2(px, m, n): 31return px*n/m 32 33 34 # 斜線函式2 35 def f3(px, m, n): 36return n-1*px*n/m 37 38 39 if __name__ == '__main__': 40r = 4# 圓半徑 41m = 8# 寬 42n = 4# 高 43a, b = (4, 4)# 圓心座標 44init() 45 46x = np.linspace(0, m, 100*m) 47y = np.linspace(0, n, 100*n) 48 49# 半圓形 50y1 = f1(x, r, a, b) 51plt.plot(x, y1) 52# 矩形橫線 53plt.plot((x.min(), x.max()), (y.min(), y.min()), 'g') 54plt.plot((x.min(), x.max()), (y.max(), y.max()), 'g') 55plt.plot((x.max(), x.max()), (y.max()+2, y.max()+2), 'g')# 畫點(8,6)避免圖形變形 56# 矩形縱向 57plt.plot((x.min(), x.min()), (y.min(), y.max()), 'g') 58plt.plot((x.max(), x.max()), (y.min(), y.max()), 'g') 59# 斜線方法 60y2 = f2(x, m, n) 61plt.plot(x, y2, 'purple') 62 63# 陰影部分填充 64xf = x[np.where(x <= 0.5*x.max())] 65plt.fill_between(xf, y.min(), f1(xf, r, a, b), where=f1(xf, r, a, b) <= f2(xf, m, n), 66facecolor='y', interpolate=True) 67plt.fill_between(xf, y.min(), f2(xf, m, n), where=f1(xf, r, a, b) > f2(xf, m, n), 68facecolor='y', interpolate=True) 69# 半圓填充 70plt.fill_between(x, y1, y.max(), facecolor='r', alpha=0.25) 71plt.show() Draw.py
2.計算原始碼,其中side是要不要計算圖形邊框上的點,理論上side只能為True;t設定越大執行時間越長也越精準
1 import numpy as np 2 3 4 def f1(px, r, a, b): 5return b - np.sqrt(r**2 - (px - a)**2) 6 7 8 def f2(px, m, n): 9return px*n/m 10 11 12 if __name__ == '__main__': 13r = 4# 圓半徑 14m = 8# 寬 15n = 4# 高 16a, b = (4, 4)# 圓心座標 17t = 100# 精度 18 19xs = np.linspace(0, m, 2*t*m) 20ys = np.linspace(0, n, t*n) 21 22# 半圓形 23y1 = f1(xs, r, a, b) 24# 斜線 25y2 = f2(xs, m, n) 26 27numin = 0 28numtotel = 0 29side = True# 是否計算邊框 30for x in xs: 31for y in ys: 32if not side: 33if (x <= 0) | (x >= 8) | (y <= 0) | (y >= 4): 34continue 35numtotel += 1 36if x >= 4: 37continue 38y1 = f1(x, r, a, b) 39y2 = f2(x, m, n) 40if y1 - y2 >= 0: 41if y2 - y > 0: 42numin += 1 43if (y2 - y == 0) and side: 44numin += 1 45elif y2 - y1 > 0: 46if y1 - y > 0: 47numin += 1 48if (y2 - y == 0) and side: 49numin += 1 50 51print(32*numin/numtotel) calc.py
四、最後小結
1.此種演算法t為100時,陰影面積為1.268;t為1000時,陰影面積為1.253,已經非常接近正確答案(正確答案1.252)
2.舉一反三,類似於這種不規則的面積,只要可以寫出來函式,就可以求解面積.
2.下面有三種求解方法,第三種表示比大學高數還難看懂,你們呢?