Skip to content

Instantly share code, notes, and snippets.

@poacosta
Created March 14, 2023 18:00
Show Gist options
  • Save poacosta/368a34620afc7e3412991445ee683e6b to your computer and use it in GitHub Desktop.
Save poacosta/368a34620afc7e3412991445ee683e6b to your computer and use it in GitHub Desktop.
Happy Pi Day! (Codewars Kumite)

Calculate Pi to a precision p.

Pi Day is an annual celebration of the mathematical constant π (pi). Pi Day is observed on March 14 (3/14 in the month/day format) since 3, 1, and 4 are the first three significant figures of π. It was founded in 1988 by Larry Shaw, an employee of the San Francisco, California science museum, the Exploratorium.

import math
from decimal import Decimal as D
from decimal import getcontext
def pi(p=5):
getcontext().prec = p
pi = D(0)
r = 8
for k in range(10000):
pi += D(math.pow(r * 2, -k)) * (D(r / 2 / (r * k + 1)) - D(2 / (r * k + 4)) - D(1 / (r * k + 5)) - D(1 / (r * k + 6)))
return str(pi)
import codewars_test as test
import solution # or from solution import example
@test.describe("Pi")
def test_group():
@test.it("with fixed precision")
def test_case():
test.assert_equals(pi(5), "3.1416")
test.assert_equals(pi(15), "3.14159265358978")
test.assert_equals(pi(25), "3.141592653589793235602542")
test.assert_equals(pi(35), "3.1415926535897932356025418121413793")
test.assert_equals(pi(45), "3.14159265358979323560254181214137928586630673")
test.assert_equals(pi(55), "3.141592653589793235602541812141379285866306715610149218")
test.assert_equals(pi(65), "3.1415926535897932356025418121413792858663067156101492186845517866")
test.assert_equals(pi(85), "3.141592653589793235602541812141379285866306715610149218684551786650252153469632637314")
test.assert_equals(pi(95), "3.1415926535897932356025418121413792858663067156101492186845517866502521534696326373091178521508")
test.assert_equals(pi(150), "3.14159265358979323560254181214137928586630671561014921868455178665025215346963263730911785215115971453711742794521158467222631243984205037768560924169")
test.assert_equals(pi(500), "3.1415926535897932356025418121413792858663067156101492186845517866502521534696326373091178521511597145371174279452115846722263124398420503776856092417015724879565153362564518846533080259991566995294581843769552520010856934537376498001876051239438261699249190309701897707607883013219006243956937026762348649953848128543102206420573056375540865249489600777954999413780342952712043852815772831475875366233547287165743683081215694880350917987858463746449719849593455892649632537572220827114424079726096699")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment