Skip to content

Instantly share code, notes, and snippets.

@realmayus
Created August 31, 2020 17:12
Show Gist options
  • Save realmayus/7ab6f37c98871a482f48f08f201096e3 to your computer and use it in GitHub Desktop.
Save realmayus/7ab6f37c98871a482f48f08f201096e3 to your computer and use it in GitHub Desktop.
Approximation of Pi using the Leibniz and the Nilkantha series, implemented in Python.
from decimal import *
getcontext().prec = 1000
# simple and beautiful but diverges slowly.
def leibniz():
prefactor = -1
pre_result = 1
current_index = 3
while True:
pre_result = Decimal(pre_result) + (Decimal(prefactor) * (Decimal(1)/Decimal(current_index)))
current_index += 2
prefactor *= -1
print("Current approximation: π = " + str(Decimal(pre_result * 4)))
# Much, much faster than Leibniz
def nilakantha():
prefactor = 1
pre_result = 3
index = 2
while True:
pre_result = Decimal(pre_result) + (Decimal(prefactor) * Decimal(Decimal(4)/Decimal(Decimal(index) * Decimal((index+1)) * Decimal((index+2)))))
index += 2
prefactor *= -1
print("Current approximation: π = " + str(pre_result))
# leibniz()
nilakantha()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment