简体   繁体   中英

Why doesn't my program approximate pi?

For yesterday's Pi Day, Matt Harper published a video in which he approximated Pi by rolling two 120-sided dice 500 times ( see the video here ). Basically, for each pair of random numbers, you have to check whether they are coprime or not. Then, the formula

pi = sqrt(6/(n_coprimes/n_cofactors))   # EDIT: Wrong premise. Misremembered the formula.

is calculated.

His result was about 3.05 which is rather close.

I wanted to see what happens when more rolls are done or when the range of random integers is increased. Interestingly, my program nearly always gave a result of 3.05 or close to it, no matter how high I set the iterations or the random range.

Here is my program. I ran it on Python 3.6 (Win64). The random number generator Python uses is supposed to be very good, so maybe I've made a mistake in my program?

import random
from math import gcd, sqrt

def pi(cp, cf):
    return sqrt(6/(cf/cp))    # EDIT: Second error - switched numerator/denominator...

coprime = 0
cofactor = 0

iterations = 1000000

for i in range(iterations):
    x = random.randint(0,1000000)
    y = random.randint(0,1000000)
    if gcd(x,y) > 1: 
        cofactor += 1
    else:
        coprime += 1

print(pi(coprime, cofactor))

I haven't watched the video, but your formula is wrong.

The probability that two ints picked randomly from 1 to N are coprime tends to 6/pi^2 as N tends to infinity. That's cp/(cf + cp) and not cp/cf.

Replacing your pi with this:

def pi(cp, cf):
    fcp = cp / float(cp + cf)
    return sqrt(6/fcp)

Gives 3.14263472915 when I run it on my machine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM