Published: 28 Sept 2017 › Updated: 28 Sept 2017
以編程來解kenchung的數學比賽
參加了 @kenchung 的 「數學 × 程式編寫比賽 (第七回)」,大家可以到這裡看看他的比賽: https://steemit.com/contest/@kenchung/question-mathematics-programming-competition-7
這是我第一次參加cn區的比賽呢! 請先看問題:
在一個正方形內隨機選取一點,並將此點與四個頂點連上直線,從而將正方形分割為四個三角形。求四個三角形之中所有內角均不超過 120° 的概率,答案準確至小數點後 3 位。
我不懂數學的解法,因此只好用程式來做。方法是不斷隨機地在正方形內抽出一點,然後用cosine theorem (怎樣也要使用一點點數學,@kenchung 真狡猾 haha) 來計算是否有超過 120° 的內角。
程式如下:
function cosThm(x1, y1, x2, y2, x3, y3){
a = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
b = Math.sqrt((x1-x3)*(x1-x3) + (y1-y3)*(y1-y3));
return Math.acos((a*a + b*b - 1)/(2 * a * b))/Math.PI * 180;
}
const numLoop = 10000000;
var count = 0;
for (var i=0; i<numLoop; i++){
x = Math.random();
y = Math.random();
if (cosThm(x, y, 0, 0, 1, 0) < 120 && cosThm(x, y, 0, 0, 0, 1) < 120 && cosThm(x, y, 0, 1, 1, 1) < 120 && cosThm(x, y, 1, 0, 1, 1) < 120) count++;
}
console.log(count/numLoop);
當時的輸出是 0.2126132
當然不太放心啦,於是就再運行了幾次,得出的頭3位小數都是0.213 (四捨五入後)
希望能得獎啦,謝謝!
Leave 以編程來解kenchung的數學比賽 to:
Read more #cn posts
Best Posts From Stand with Hong Kong
We have not curated any of vincentyip's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.