Skip to content

Instantly share code, notes, and snippets.

@yoh2
Last active September 20, 2017 17:54
Show Gist options
  • Save yoh2/3f9e66e224b13572bfae4c89027fae06 to your computer and use it in GitHub Desktop.
Save yoh2/3f9e66e224b13572bfae4c89027fae06 to your computer and use it in GitHub Desktop.
2人の子供のうち少なくとも一方が女の子の時もう一方も女の子である確率 のモンテカルロ法
#!/usr/bin/perl -w
use strict;
my $total = 0; # どちらか一方が女の子であった数
my $n = 0; # もう一方も女の子 (つまりふたりとも女の子) であった数
foreach(0 .. 10000)
{
# ふたり分の性別。男の子: 0, 女の子: 1 とみなす。
my ($x, $y) = (int(rand(2)), int(rand(2)));
if (($x == 1) || ($y == 1))
{
$total++;
$n++ if $x == $y;
}
}
printf("total = %d, n = %d, p = %f\n", $total, $n, $n / $total);
#!/usr/bin/perl -w
use strict;
# 問題の解釈の仕方を変えたパターン。この場合は 1/2 に。
my $total = 0; # どちらか一方が女の子であった数
my $n = 0; # もう一方も女の子 (つまりふたりとも女の子) であった数
foreach(0 .. 10000)
{
# このパターンだと「女の子はいますか?」と聞いたパターンじゃなくて
# 「上の子は女の子ですか?」または「下の子は女の子ですか?」
# と聞いたパターンになり、問題文からの解釈としては無理がありそう。
# ふたり分の性別。男の子: 0, 女の子: 1 とみなす。
my ($x, $y) = (int(rand(2)), int(rand(2)));
# 上の子 (xを上の子としてます) を聞いたら女の子だったパターン
if ($x == 1)
{
$total++;
$n++ if $y == 1;
}
# 下の子を聞いたら女の子だったパターン
if ($y == 1)
{
$total++;
$n++ if $x == 1;
}
}
printf("total = %d, n = %d, p = %f\n", $total, $n, $n / $total);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment