Reputation: 45
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")
Your program should prompt the user for the number of attempts to perform and print the ratio attempts/hits as a floating point number after all the attempts have completed.
How do I get the ratio of attempts/hits?
Upvotes: 1
Views: 1758
Reputation: 6519
If you don't mind using numpy, here's an alternate solution:
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)
Upvotes: 0
Reputation: 9909
Store the number of hits in a variable, increment it when a hit occurs and print the ratio after iterating.
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))
Upvotes: 3