Skip to content

Instantly share code, notes, and snippets.

@sean-lin
Last active January 17, 2017 04:09
Show Gist options
  • Save sean-lin/6cd3f9b33d454b50ffcd38a241027df6 to your computer and use it in GitHub Desktop.
Save sean-lin/6cd3f9b33d454b50ffcd38a241027df6 to your computer and use it in GitHub Desktop.
import random
TEST_N = 10000000
def calc(target):
rate_max = 1
rate_min = 0
while True:
rate = dt = (rate_max + rate_min)/2.0
hit = 0
for i in xrange(TEST_N):
if random.random() < rate:
hit += 1
rate = dt
rate += dt
now = hit * 1.0 / TEST_N
if abs(now - target) < 0.0001:
return dt
if now > target:
rate_max = dt
else:
rate_min = dt
if rate_max < rate_min:
return dt
rate = calc(0.1)
print "rate:", rate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment