參加了 @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 (四捨五入後)
希望能得獎啦,謝謝!
不錯啊,你的程式挺簡單,可能要比數學方法還要快呢~
Congratulations @vincentyip, this post is the seventh most rewarded post (based on pending payouts) in the last 12 hours written by a Dust account holder (accounts that hold between 0 and 0.01 Mega Vests). The total number of posts by Dust account holders during this period was 3610 and the total pending payments to posts in this category was $937.49. To see the full list of highest paid posts across all accounts categories, click here.
If you do not wish to receive these messages in future, please reply stop to this comment.
加油加油!学习了。
Congratulations @vincentyip! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
You got your First payout
Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here
If you no longer want to receive notifications, reply to this comment with the word
STOP