Need π to 100 or so digits precision?

March 17, 2015 | Math | By: Mark VandeWettering

Use the “bc” arbitrary precision calculator you can probably find (or install easily) on your Linux box.

> bc -l
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
scale=50
4*a(1)
3.14159265358979323846264338327950288419716939937508

User input is in bold. the scale command sets the number of digits of precision. If you need 200 digits…

scale=200
4*a(1)
3.141592653589793238462643383279502884197169399375105820974944592307\
81640628620899862803482534211706798214808651328230664709384460955058\
223172535940812848111745028410270193852110555964462294895493038196

Other formulas work pretty well too:

4*(4*a(1/5)-a(1/239))
3.141592653589793238462643383279502884197169399375105820974944592307\
81640628620899862803482534211706798214808651328230664709384460955058\
223172535940812848111745028410270193852110555964462294895493038188

Note: the last few digits are likely to be off, so generate a few more than you need. For fun, try to set the number of digits to a couple of thousand digits, and compare the runtime of each of the formulas.

Addendum: You can use the Gauss-Legendre algorithm to compute the digits of pi using bc as well. If you double the “scale”, you’ll need to add one to the for loop variable.

scale=1000

define sqr(x) {
    return x * x ;
}

a = 1 
b = 1 / sqrt(2)
t = 1 / 4
p = 1

for (i=0; i<9; i++) {
    next_a = (a + b) / 2
    next_b = sqrt(a * b)
    next_t = t - p * sqr(a - next_a)
    next_p = 2 * p

    a = next_a
    b = next_b
    t = next_t
    p = next_p
}

sqr(a + b) / (4 * t)