Language
Python
Compiler
CPython 3.10.2
Options
import random
# 確率pでTrue、1-pでFalseを返す
def randBool(p):
return random.random() < p
# 男子の生まれる確率がpのときのシミュレーションを1回行い、子供の数を返す
def simulate(p):
numChildren = 1
firstChild = randBool(p)
while True:
numChildren += 1
newChild = randBool(p)
if firstChild == newChild:
return numChildren
# 男子の生まれる確率がpのときのシミュレーションをnum回行い、子供の数の平均を返す
def repeatSimulation(p, num):
results = [simulate(p) for _ in range(num)]
return sum(results) / len(results)
numSimulation = 100000
# p = 0.01 から 0.99 まで 0.01 刻みでシミュレーションを行う
for i in range(1, 100):
p = i / 100.0
print("%.2f %f" % (p, repeatSimulation(p, numSimulation)))
$ python3 prog.py
0.01 3.053620
0.02 3.011690
0.03 2.993910
0.04 3.037800
0.05 2.971620
0.06 3.018160
0.07 3.000110
0.08 2.990430
0.09 3.022200
0.10 3.005660
0.11 2.999660
0.12 3.011140
0.13 3.015850
0.14 2.978760
0.15 2.996060
0.16 2.996070
0.17 3.006340
0.18 2.998220
0.19 2.986060
0.20 3.004720
0.21 3.000840
0.22 3.003630
0.23 2.992840
0.24 2.995920
0.25 3.001060
0.26 2.999150
0.27 2.992830
0.28 3.002380
0.29 3.005200
0.30 3.014490
0.31 2.997380
0.32 2.990870
0.33 2.993910
0.34 3.000160
0.35 2.996810
0.36 3.004260
0.37 2.996420
0.38 2.993200
0.39 2.998120
0.40 3.003820
0.41 3.000870
0.42 2.994020
0.43 3.000610
0.44 2.996700
0.45 2.994600
0.46 2.998030
0.47 2.998260
0.48 2.991130
0.49 3.012400
0.50 3.007970
0.51 2.996500
0.52 3.004880
0.53 3.005360
0.54 2.995460
0.55 2.997430
0.56 2.996730
0.57 2.995340
0.58 3.000500
0.59 2.991520
0.60 3.004460
0.61 3.003800
0.62 3.003170
0.63 3.003530
0.64 2.996680
0.65 2.993340
0.66 2.997740
0.67 3.006910
0.68 2.997690
0.69 2.999090
0.70 2.993060
0.71 2.999760
0.72 2.998020
0.73 2.992980
0.74 2.983850
0.75 2.994730
0.76 3.013340
0.77 2.994420
0.78 3.000630
0.79 2.993440
0.80 3.000710
0.81 3.017460
0.82 3.001210
0.83 3.001580
0.84 3.003550
0.85 3.011010
0.86 2.998420
0.87 2.995380
0.88 2.979570
0.89 3.008700
0.90 2.999220
0.91 2.981940
0.92 3.003340
0.93 3.008350
0.94 3.015690
0.95 3.015350
0.96 2.986300
0.97 2.967750
0.98 2.985260
0.99 2.996780
Exit Code:
0