# Pi Calculation Code Golf [closed]

## The Challenge

You must calculate pi in the shortest length you can. Any language is welcome to join and you can use any formula to calculate pi. It must be able to calculate pi to at least 5 decimal places. Shortest, would be measured in characters. Competition lasts for 48 hours. Begin.

Note: This similar question states that PI must be calculated using the series 4 * (1 – 1/3 + 1/5 – 1/7 + …). This question does not have this restriction, and in fact a lot of answers here (including the most likely to win) would be invalid in that other question. So, this is not a duplicate.

• @hvd Why do you think it should be disqualified? It fits the specs ... – Dr. belisarius Feb 24 '14 at 21:53
• @hvd acos(-1). I win! – Level River St Feb 24 '14 at 23:47
• This looks weird, inconsistent. Calculating π has to be dividing a circle by its diameter, or some other operation giving π. If we accept doing 355/113 — which has nothing to do with π except luck —, like @ace, then logically we should accept doing 3.14159. – Nicolas Barbulesco Feb 25 '14 at 20:07
• I don't get why people like this question. This is one of the most ill-defined and uninteresting questions I've seen on here. The only difference between this and hello world, is that this has something to do with Pi. – Cruncher Feb 25 '14 at 21:54
• To make this question interesting it needs a scoring function that rewards digits of pi per byte of code. – Ben Jackson Feb 26 '14 at 5:16

## R

A few years back I was taking a math course and the instructor asked the class how we might compute pi from scratch. A guy at the back of the class suggested drawing a circle of diameter 1 and then laying a piece of string around it.

I couldn't figure out how to do that in R. I decided the second most primitive approach would be to approximate the circle with a regular polygons. A 4096-gon gets us 5 digits. The polygons are approximated with a simple binary search using only the midpoint and distance formulae (i.e. no trigonometric functions are used).

a <- c(0,1); b <- c(0,0); c <-c(1,0)
eps <- 0.000000001
mid  <- function(a,b) { c(mean(c(a[1],b[1])), mean(c(a[2],b[2])))}
dist <- function(a,b) { sqrt((a[1]-b[1])^2 + (a[2]-b[2])^2)}
for (i in 1:10)
{
ab1 <- mid(a,b)
ab2 <- mid(b, ab1)
bc1 <- mid(b,c)
bc2 <- mid(b, bc1)
repeat
{
newab <- mid(ab1,ab2)
newbc <- mid(bc1, bc2)
corner <- dist(newab,newbc)
side   <- dist(a,b) - 2*dist(newab,b)
dif <- side - corner
if (abs(dif) < eps)
{
a <- c(0,newab[2]+dist(newab,newbc))
b <- newab
c <- newbc
break
}
if (dif > 0){ab2 <- newab;bc2 <- newbc}
if (dif < 0){ab1 <- newab;bc1 <- newbc}
}
}
print((2^(i+2))*dist(newab,newbc))


# Python, 37 chars

Using zeta(10) for fast convergence:

    sum(93555./i**10 for i in[1,2,3])**.1
3.1415923154068


Using the same serie to get 15 correct digits:

    sum(93555./i**10 for i in range(1,40))**.1
3.141592653589793


53 characters of Javascript:

x=3;d=1;while(d>1e-8){d=Math.sin(x);x+=d;};alert(x);

With an arbitrary numeric precision implementation of sin (e.g. taylor expansion), this will give an arbitrarily exact result with good convergence and a roughly estimated precision while keeping the code very simple.

• Save some characters with alert(x), and also remove the var statements – scrblnrd3 Mar 2 '14 at 10:59

# TI CAS , 4

180°


If you really insist, to put it into radians mode:

Radians:180°


(suggested by AJMansfield)

• Assuming you're in radians mode is dangerous, as in "assuming you have Pi/2 loaded in some var". If that's the machine default, it's Ok (I think). If it's not the default mode you should include the appropriate settings. If the settings aren't programmable, the environment can't compete. – Dr. belisarius Feb 24 '14 at 22:26
• Agreed with @belisarius I'd consider Radian->Mode or similar at least 10 chars. – Timtech Feb 24 '14 at 22:28
• Radian mode is the default – TheDoctor Feb 24 '14 at 22:44
• Ok! Just a rant: I don't like this one (or my answer, or a lot of other ones around). We are just exploiting a weak problem definition. – Dr. belisarius Feb 24 '14 at 23:15
• At least on the TI-84 (on which this is also a legal program), the command token for changing modes is only 2 bytes. Just insert Radians: at the beginning, and you have a 7 char program that works regardless of the current mode. – AJMansfield Feb 25 '14 at 1:32

AppleScript, 8 characters

Solution :

3+.14159


Result :

3.14159

• When you have one sourcecode that works on multiple languages, it is better to post only one answer and include the name of both languages in the same answer. – user12205 Feb 25 '14 at 21:53

# Python - 68 characters

Quite a long solution.

_=lambda x,y=1:x^y and y*2-1+y**2/_(x,y+1)or x*2.0+1
print 4/_(99)


# bc -l, 6

4*a(1)


This requires the -l option to bc. Do I need to declare extra points for that?

Using -l calculates to 20 decimal places:

$bc -l<<<"4*a(1)" 3.14159265358979323844$

• I don't think 4 * atan(1) really qualifies as calculating anything. All these answers with trig functions eventually rely on pi itself being part of the equation at some point; it's really a glorified 4 * pi / 4. – Jason C Feb 26 '14 at 4:03
• @JasonC - point taken. So here's another answer which I think should satisfy your thirst for real calculation ;-) – Digital Trauma Feb 26 '14 at 18:23
• I count 6 chars, not 7! – F. Hauri Feb 27 '14 at 7:58
• @JasonC In fact, you are partialy right in that: bc use precomputed strings for quick answer on less than 60 decimal presicion calculation: see source code but if presicion requested if greater than 60 decimals, then bc will effectively compute the answer. – F. Hauri Feb 27 '14 at 8:22
• @JasonC so if I read the source code correctly, then -4*a(-1) would be a valid answer, as precomputed strings are only given for x=1 and 0.2. The arctan() is computed using one of two convergent series, neither of which has any pre-computed knowledge of Pi, when x=-1. – Digital Trauma Feb 27 '14 at 21:12

# Groovy, 77

def x=0;for(k in 0..99){x+=Math.pow(-1/3,k)/(2*k+1)};println x*Math.sqrt(12)


This uses the Madhava-Leibniz series, which converges more quickly than the plain Leibniz series:

Output:

3.141592653616969

AppleScript, 4 characters !

Solution :

pi+0


Displayed result :

3.14159265359


# TI BASIC, 24

Disp fnInt(√(4-X²),X,0,2


returns:

3.141593074
Done


This does not use any trig function, instead it uses numerical integration of the function of half a circle with radius 2. That circle has area 4pi, so half that circle has area 2pi, but i integrate from 0 to 2 wich is half of that, so a quarter of the circle, area pi.

## Groovy: 25

print Math.log(10691/462)


Output is 3.141592653932079

de Jerphanion approximation

## Windows Calculator - cheat: 1, less cheating: 5

p (not my final answer, but I just had to include this for lulz)

or

F₁ 1 i t * 4 ↲
F₄ 1 F₉ i o

(F₄ sets mode to radians, F₉ negates the buffer)

If it must be a pasteable/savable string, and mode is already set to radians and the buffer is 0.0: io*2=

# APL : 2 chars

    ○1
3.141592653589793


# Julia

Hiperarmonic series:

julia> s=0;sqrt(6*([s+=1/i^2 for i=1:8^6][end]))
3.1415890108270967


Zeta function:

julia> sqrt(zeta(2)*6)
3.141592653589793


Bailey-Borwein-Plouffe formula:

julia> s=0;[s+=(-1)^k/4^k*(2/(4k+1)+2/(4k+2)+1/(4k+3)) for k=0:7]
8-element Array{Any,1}:
3.33333
3.11429
3.14636
3.14068
3.14178
3.14155
3.1416
3.14159


Ramanujan formula (fastest convergence):

julia> !n=factorial(n);s=0;([s+=!4n*(1103+26390n)/(!n*396^n)^4 for n=0][end]*(sqrt(8)/9801))^-1
3.1415927300133055


## Javascript 44

I am new to golfing, so this is my best shot:

p=0;for(i=1;i<1e7;i+=4)p+=8/i/(i+2);alert(p)


# JavaScript 50 (30 decimal places, including alert call...)

alert((m=Math).log(pow(640320,3)+744)/pow(163,.5))
....5....0....5....0....5....0....5....0....5....0


Based on the entry under Miscellaneous Approximations section in wikipedia: http://en.wikipedia.org/wiki/Approximations_of_%CF%80

Or for less accurate...

# JavaScript 40 (10 decimal places, including alert call)

alert(Math.pow(1e100/11222.11122,1/193))
....5....0....5....0....5....0....5....0


Output:

3.1415926536438223
...........^ Accuracy finishes after this digit!)


Or for even less accurate...

# JavaScript 28 (8 decimal places, including alert call!)

alert(Math.pow(2143/22,.25))
....5....0....5....0....5..8


Output:

3.1415926525826463
.........^ Accuracy finishes after this digit!)

• alert(Math.pow(2143/22,.25) gives me a syntax error. did you forgot the last ) ? – Wolle Vanillebär Lutz Feb 28 '14 at 15:29
• @WolleVanillebarLutz Oops! Fixed! – WallyWest Feb 28 '14 at 22:38

# Smalltalk, 9

1arcSin*2


will do

• How is using somebody else's implementation of trig identities that rely on pi to begin with in the spirit of this question? – Jason C Feb 26 '14 at 4:09
• in the same spirit as acos, swrt, fpatan, degrees-to-radians, tan. I agree in general, but I don't see why your particularly blaming me. And btw: why "someone else's" ? – blabla999 Feb 26 '14 at 18:56

# q [7 chars]

acos -1


### Example

acos -1
3.141593

355%113       // [7 Chars]
3.141593

2*asin 1      // [8 Chars]
3.141593


## Python : 8 bytes

acos(-1)


do i have to include imports??

• This is 8 bytes, not 7. At least it is definitely 8 characters. (Aside from the fact that my identical version of this in the question comments predates this by 1 hour.) – Level River St Feb 25 '14 at 6:22
• Yes, you have to include imports. – user12205 Feb 25 '14 at 18:55

## Ruby, 35

Using Euler's formula. No reliance on trigonometric functions that might store π somewhere (though CMath might use Math::PI internally...).

require('cmath');CMath.log(-1).imag


Returns

3.141592653589793


## Java: 89

class j{public static void main(String[]a){System.out.print(4-Math.pow(105./166,1./3));}}


unGolfed:

class j {
public static void main(String a[]){
//E. Pegg approximation
System.out.print(4-Math.pow(105./166,1./3));
}
}


Python, 27

import math
math.atan(1)*4

• I'm morally opposed to this cop-out solution, but you can make it even shorter. __import__('math').atan(1)*4 -- 28, and it prints the result in the REPL shell. – amcgregor Feb 27 '14 at 20:56

This was originally a comment to this answer, but since the full program is shorter than the other C solution (which is only a function), I might as well post it as an answer:

# C, 64

double x,i;main(){for(;i++<1e8;)x+=6/i/i;printf("%f",sqrt(x));}


output:

3.141593


# C

main(){printf("%f",22/7.0);}

• "It must be able to calculate pi to at least 5 decimal places." – mbomb007 Jan 14 '15 at 15:40

### bc -l, 9 chars

2*a(2^99)


Even with bc(1)'s default scale this is correct up to as many digits as I memorised. Raise the potence (and the scale) to get more precisions.

## PHP, 281

Not going to win, but more of a challenge for myself.

Calculates PI to the nth precision (determined by the value of $d, currently 5). This is a PHP implementation of the Gauss–Legendre algorithm. I discovered after the fact this was almost exactly done by someone 7 years ago... *smh* ...posting anyway. Golfed: $d=5;$r=$d+4;$n=floor(log($r)/log(2));bcscale($r);$a=1;$b=bcdiv(1,bcsqrt(2));$t=.25;$p=1;while($n--){$x=bcdiv(bcadd($a,$b),2);$y=bcsqrt(bcmul($a,$b));$t=bcsub($t,bcmul($p,bcsub(bcpow($x,2),bcpow($y,2))));$p=bcmul(2,$p);$a=$x;$b=$y;}echo bcdiv(bcpow(bcadd($a,$b),2),bcmul(4,$t),$d);  $d = 5 outputs 3.14159

$d = 19 outputs 3.1415926535897932384 $d = 41 outputs 3.14159265358979323846264338327950288419716

etc...

Community Help: I would like to set the scale/precision more appropriately on each iteration (rather than fixed at 4: $r=$d+4), but I can't seem to find a way to reliably determine the error precision, i.e. the rate of convergence isn't constant.

# Java 8, 155

class P{public static void main(String[] s){System.out.print(4*java.util.stream.IntStream.range(0,999999).mapToDouble(x->Math.pow(-1,x)/(2*x+1)).sum());}}


Uses the same approach as @HeikoOberdiek's Perl solution i.e., the Leibniz formula.

Here's the same program in a longer form, formatted for easier reading:

import static java.lang.Math.pow;
import static java.util.stream.IntStream.range;

public class Pie {
public static void main(String[] args) {
System.out.println(4 * range(0, 999_999).mapToDouble(x -> pow(-1, x) / (2*x + 1)).sum());
}
}


Output:

3.1415936535907933

• I chose not to use @Navin's static block trick as I'm not sure whether it's valid. – David Conrad Mar 4 '14 at 18:16
• Also, one other difference between this and @HeikoOberdiek's Perl program is that this goes over the range [0, 999,999) whereas the Perl uses the range [0, 999,999]. I could change the constant to 1_000_000 or use rangeClosed instead of range, but those would both increase the character count. – David Conrad Mar 4 '14 at 18:23

# JavaScript, 94 characters

+function p(n){return~n?(4/(8*n+1)-1/(4*n+2)-1/(8*n+5)-1/(8*n+6))/Math.pow(16,n)+p(n-1):0}(9)

• Can somebody help me golf this further with some bitshifts? – Simon Kuang Aug 7 '14 at 4:53

## R, Monte Carlo 68

Old square inscribed in circle method.

z=n=0;repeat{z=z+ifelse(sum(runif(2)^2)<1,1,0);n=n+1;write(4*z/n,1)}


Check if x^2 + y^2 <= r^2, if yes z += z, else n += n. Pi ~= 4z/n as iteration -> inf.

## C++ 26

main(){cout<<6*asin(0.5);}