Skip to content

Instantly share code, notes, and snippets.

@youz
Last active May 29, 2022 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save youz/4feadfa5a2dac49a15892d03e9fdf883 to your computer and use it in GitHub Desktop.
Save youz/4feadfa5a2dac49a15892d03e9fdf883 to your computer and use it in GitHub Desktop.
Computing the digits of π in PostgreSQL
-- ref https://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf
with recursive pigen(q, r, t, i, y, n) as (
select 1::decimal, 180::decimal, 60::decimal, 2, 0::decimal, 0
union all select 10*q*i*(2*i-1), 10*u*(q*(5*i-2)+r-y*t), t*u, i+1, y, n+1
from (select q, r, t, i, n, 3*(3*i+1)*(3*i+2) as u, div(q*(27*i-12)+5*r,(5*t)) as y from pigen) as tmp
where n < 1000
)
select string_agg(y::text, '') pi
from pigen where n > 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment