Question About Python Loop 1. Write a function for_pi(n) that takes a positive i
ID: 3902236 • Letter: Q
Question
Question About Python Loop
1. Write a function for_pi(n) that takes a positive integer n and returns an estimate of Tu that is based on n randomly thrown darts. The function should use a loop and the throw_dart function to throw the n darts. After each dart is thrown, the function should print the following: the number of darts thrown so far the number of the darts that have hit the circle the current estimate of ? Then, after all n throws have been made, the function should return the final estimate of ?. Because the throw_dart function is using random numbers, the results obtained for a given input will vary. However, here's one example of what the output should look like: >for_pi(10) 1 hits out of 1 throws so that pi is 4.0 2 hits out of 2 throws so that pi is 4.0 3 hits out of 3 throws so that pi is 4.0 4 hits out of 4 throws so that pi is 4.0 4 hits out of 5 throws so that pi is 3.2 5 hits out of 6 throws so that pi is 3.33333333333 6 hits out of 7 throws so that pi is 3.42857142857 6 hits out of 8 throws so that pi is 3.0 7 hits out of 9 throws so that pi is 3.11111111111 8 hits out of 10 throws so that pi is 3.2 3.2Explanation / Answer
import random,math
totalThrows=90000
throwsInsideCircle = 0
for throw in xrange(totalThrows):
x = random.random()*2 -1
y = random.random()*2 -1
if(x*x + y*y <= 1.0):
throwsInsideCircle += 1
# compute pi
pi = (4.0*throwsInsideCircle)/totalThrows
print(pi)