Skip to content

Instantly share code, notes, and snippets.

@PM2Ring
Last active October 4, 2023 06:58
Show Gist options
  • Save PM2Ring/a4655b6029d78d449a8aa28c3986bf89 to your computer and use it in GitHub Desktop.
Save PM2Ring/a4655b6029d78d449a8aa28c3986bf89 to your computer and use it in GitHub Desktop.
Carlson arcsin demo. Calculates pi.
""" pi from 10 * asin((phi-1)/2)
Uses Carlson's accelerated version of
Borchardt's modified AGM algorithm
Written by PM 2Ring 2022.05.11
"""
from itertools import count
from decimal import Decimal as D, getcontext
def agm_asin(x):
ctx = getcontext()
eps = 16 / D(10) ** ctx.prec
ctx.prec += 2
b = one = D(1)
a = (one - x*x).sqrt()
g = one
d = [a]
for i in count(1):
a = (a + g) / 2
pd, d = d, [a]
q = one
for u in pd:
q /= 4
d.append(d[-1] - u * q)
r = one - q
b *= r
y = b * x / d[-1]; print(f"{i:2}: {y}")
if abs(pd[-1] * r - d[-1]) < eps:
break
g = (a * g).sqrt()
#y = b * x / d[-1]
ctx.prec -= 2
return +y
ctx = getcontext()
ctx.prec = 50
x = (D(5).sqrt() - 1) / 4
y = agm_asin(x)
print(10 * y)
@PM2Ring
Copy link
Author

PM2Ring commented Dec 31, 2022

Live demo running on SageMathCell.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment