割箸三角形問題
https://twitter.com/t_kohyama/status/833592761689395202 https://gyazo.com/ae58bb45191d2fc2e141aeb13d76fe3b
code:waribashi.js
function setup(){
$('<h2>').text('割箸をランダムに3分割したとき三角形を作れる確率を計算').appendTo($('body'))
createCanvas(600,400)
count = 0
success = 0
frameRate(10)
}
function draw(){
rand1 = random()
rand2 = random()
count++
l1 = rand1
l2 = rand2-rand1
l3 = 1-rand2
clear()
stroke('red')
strokeWeight(3)
line(l1*400,300,0,300)
line((l1+l2)*400,300,400,300)
stroke('blue')
line(l1*400,300,(l1+l2)*400,300)
if(l1 < l2+l3 && l2 < l1+l3 && l3 < l1+l2){ // 三角形が成立
success++
// l1, l2, l3の三角形を描画
fill('blue')
strokeWeight(5)
c = (l1 * l1 + l2 * l2 - l3 * l3) / (2 * l1 * l2) // 余弦定理
s = sqrt(1 - c * c)
p1x = l1 + l1 * c
p1y = 0 + l1 * s
triangle(l1*400,300,(l1+l2)*400,300,p1x*400,300-p1y*400)
}
fill('black')
strokeWeight(0)
text(確率: ${success/count}, 20, 20)
}