from random import random
from math import pi, sin
attempts = int(input("Enter the number of attempts to perform: "))
for i in range(1,attempts):
ytail = 2.0*random()
angle = pi*random()
yhead = ytail + sin(angle)
if yhead > 2.0:
print ("hit")
else:
print ("not a hit")
您的程序应提示用户尝试执行的次数,并将比率尝试/命中数作为浮点打印 所有尝试完成后的数字。
如何获得尝试/命中率?
答案 0 :(得分:2)
将命中数存储在变量中,在命中时将其递增,并在迭代后打印该比率。
from random import random
from math import pi, sin
hits = 0
attempts = int(input("Enter the number of attempts to perform: "))
for i in range(0, attempts):
ytail = 2.0 * random()
angle = pi * random()
yhead = ytail + sin(angle)
if yhead > 2.0:
hits += 1
print(hits / float(attempts))
答案 1 :(得分:0)
如果你不介意使用numpy,这是另一种解决方案:
import numpy as np
attempts = int(input("Enter the number of attempts to perform: "))
ytail = 2.0*np.random.rand(attempts)
angle = np.pi*np.random.rand(attempts)
yhead = ytail + np.sin(angle)
print(np.sum(yhead > 2.0)/attempts)