Killing Time With Recreational Math - Two Weird Ways to Calculate Pi (Using Python)

in #steemstem6 years ago (edited)

Pi is an irrational number that it defined as the ratio of the circumference of a circle divided by its diameter.

In an ancient times the value of pi was calculated mathematically by drawing regular polygons with many sides and adding up the length of the sides and dividing by that shape's width.

Also it could be done "experimentally" by wrapping a string around a circle, measuring the length of the string and then dividing by the diameter of that circle.

These days there are many ways of calculating pi, some fast, some slow. In this post I will present two of the more unusual ways of calculating pi.

Method #1: Random darts thrown at a circle

The area of a circle is known to be A = πr2. Imagine that you have a circle inscribed in a square, the width of the square is the same as the diameter of the circle.

Now you throw darts at this circle perfectly randomly. If you count the number of darts that fall inside the circle and divide that by the total number of darts you can estimate the value of pi.

You can achieve this by creating a random number 'x', another random number 'y' and defining them to be a point in the upper right quadrant of a unit square (a unit square is a square where the sides have length 1).

The distance from the origin can be calculated using Pythagoras' Theorem. If the distance is greater than 1 then it falls outside the unit circle (a unit circle is a circle with radius 1).

In this algorithm we are only simulating darts being thrown at a quarter circle in a square. The circle has a radius of 1 so its area will be equal to π/4.

The number of darts that fall within the quarter circle will therefore also be equal to π/4.

Let's run the code and see what we get.

# Released under CC BY-SA 4.0 license by procrastilearner.
import math
import random
import time
import datetime
from fractions import gcd

DT = datetime.datetime.now()
print("Start time = " + str(DT))
random.seed(DT)

num_matches = 0
num_trials = 100000000
innerloop = num_trials/100
outerloop = num_trials/innerloop
pi=0.
area=0

for i in range(0, num_trials):
    x = random.random()
    y = random.random()
    D = math.sqrt(x**2 + y**2)
    if D < 1: area+=1

pi = 4*area/float(num_trials)
print("number of trials = " + str(num_trials))
print("pi = " + str(pi))

DT = datetime.datetime.now()
print("Finish time = " + str(DT))

The Result

After 100,000,000 trials (100 million) and just over 2 minutes of computer time I get a result of 3.14150768 which is good to the 4th decimal place.

Not the fastest way to calculate pi but it is both an interesting way and also a visually intuitive way to do that task.

Method #2: Co-Prime Integers

In a post about 2 months ago A Slow Boat to "π-na" I showed how to calculate pi in Excel using random numbers and checking if they were co=prime.

Basically, if you create a long list of random integer pairs and determine the fraction that are co-prime you can calculate the value of π using this relation:

where f is the fraction of integer pairs that are co-prime. Solving for π we get:

I have converted that Excel spreadsheet into the following Python program:

# Released under CC BY-SA 4.0 license by procrastilearner.
import math
import random
import time
import datetime
from fractions import gcd

DT = datetime.datetime.now()
print(DT)
random.seed(DT)

num_matches = 0
num_trials = 100000001
pi=0

for i in range(1, num_trials):
    x1 = 1+int(100000000*random.random())
    x2 = 1+int(100000000*random.random())

    if gcd(x1,x2)>1:
        num_matches += 1
        
ratio = float(num_matches)/float(num_trials)
ratio = 1 - ratio
pi = math.sqrt(6.0/ratio)

DT = datetime.datetime.now()
print("Iterations = " + str(i))
print("Number of coprime matches = " + str(num_matches))
print("Ratio R =" + str(ratio))
print("pi = " + str(pi))
print(DT)

The Result

After 100,000,000 trails (100 million) and about 11 minutes we get a value of pi to be calculated be 3.141480049843734 which is really only good to 3 decimal places.

This has to be the single most slowest way to calculate pi. I have a feeling that it is actually testing the quality of the random function in Python more than it is calculating pi.

Closing Words

There are many ways to calculate pi and most of them are faster than the two methods demonstrated here in this post by these two Python programs.

However the first method is interesting because it is more visually intuitive and it uses random 'darts' thrown at a 'dart board'.

The second method is more unusual and surprising because it relates the random numbers to the value of pi. In this case the relation is whether those two randomly picked numbers were co-prime.

Thank you for reading my post.

Other Posts In My Recreational Math Series

  1. Testing the excel random function.
  2. Make Your Own Bell Curve.
  3. Strange Attractors.
  4. Let's Travel To Alpha Centauri.
  5. Calculate Sunset and Sunrise Times.
  6. Conway's Game of Life.
  7. Caffeine Half-Life.
  8. Let's Simulate a Radioactive Sample.
  9. A Slow Boat to "π-na".
  10. Journey Through the Centre of Psyche.
  11. Star Trek Into Darkness.
  12. Calculate Sunrise and Sunset Times Using Python.

Post Sources

YouTube Video: Generating π from 1,000 random numbers.
Co-prime Integers
Estimating Pi using the Monte Carlo Method
Pyhthon.org

Sort:  

Great. Unusual and very interesting as always. Thanks!

Very cool! Thanks!

Hi @procrastilearner!

Your post was upvoted by utopian.io in cooperation with steemstem - supporting knowledge, innovation and technological advancement on the Steem Blockchain.

Contribute to Open Source with utopian.io

Learn how to contribute on our website and join the new open source economy.

Want to chat? Join the Utopian Community on Discord https://discord.gg/h52nFrV

Coin Marketplace

STEEM 0.33
TRX 0.11
JST 0.034
BTC 66598.01
ETH 3236.65
USDT 1.00
SBD 4.66