coin_tossing_simulation_with_probabilities.py
· 717 B · Python
原始文件
import random
def toss_coin():
# 0代表正面,1代表反面
return "正面" if random.randint(0, 1) == 0 else "反面"
def simulate_tosses(n):
# 初始化計數器
count_heads = 0
count_tails = 0
# 擲硬幣n次
for _ in range(n):
result = toss_coin()
if result == "正面":
count_heads += 1
else:
count_tails += 1
# 計算機率並轉換為百分比
prob_heads = round((count_heads / n) * 100, 2)
prob_tails = round((count_tails / n) * 100, 2)
print(f"正面出現的機率是:{prob_heads}%")
print(f"反面出現的機率是:{prob_tails}%")
# 呼叫函數,擲硬幣1000000次
simulate_tosses(1000000)
| 1 | import random |
| 2 | |
| 3 | |
| 4 | def toss_coin(): |
| 5 | # 0代表正面,1代表反面 |
| 6 | return "正面" if random.randint(0, 1) == 0 else "反面" |
| 7 | |
| 8 | |
| 9 | def simulate_tosses(n): |
| 10 | # 初始化計數器 |
| 11 | count_heads = 0 |
| 12 | count_tails = 0 |
| 13 | |
| 14 | # 擲硬幣n次 |
| 15 | for _ in range(n): |
| 16 | result = toss_coin() |
| 17 | if result == "正面": |
| 18 | count_heads += 1 |
| 19 | else: |
| 20 | count_tails += 1 |
| 21 | |
| 22 | # 計算機率並轉換為百分比 |
| 23 | prob_heads = round((count_heads / n) * 100, 2) |
| 24 | prob_tails = round((count_tails / n) * 100, 2) |
| 25 | |
| 26 | print(f"正面出現的機率是:{prob_heads}%") |
| 27 | print(f"反面出現的機率是:{prob_tails}%") |
| 28 | |
| 29 | |
| 30 | # 呼叫函數,擲硬幣1000000次 |
| 31 | simulate_tosses(1000000) |
| 32 |