Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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.

share|improve this question
3  
@hvd Why do you think it should be disqualified? It fits the specs ... –  belisarius Feb 24 at 21:53
4  
@hvd acos(-1). I win! –  steveverrill Feb 24 at 23:47
3  
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 at 20:07
5  
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 at 21:54
5  
To make this question interesting it needs a scoring function that rewards digits of pi per byte of code. –  Ben Jackson Feb 26 at 5:16

63 Answers 63

Python3, 7

Runs in the interactive shell

355/113

Output: 3.1415929203539825, correct to 6 decimal places

And finally I have a solution that beats APL!

Oh, and in case you are wondering, this ratio is called the 密率 (literally "precise ratio"), and is proposed by the Chinese mathematician Zu Chongzhi (429-500 AD). A related wikipedia article can be found here. Zu also gave the ratio 22/7 as the "rough ratio", and he is known to be the first mathematician to propose that 3.1415926 <= pi <=3.1415927

share|improve this answer
11  
mhmh - that is actually a polyglot answer. Works in Smalltalk too! –  blabla999 Feb 24 at 22:02
6  
Blasphemy! It's barely a calculation! –  mniip Feb 24 at 22:08
25  
The awkward moment when I wrote this as a serious answer but everyone interprets it as a joke... –  ace Feb 25 at 19:50
3  
This answer works also in the google search. Pretty nifty! –  gvsrepins Feb 25 at 21:17
9  
Highest voted answer: 355/113. Lowest voted answer: 3+.14159. I don't see much difference, really. –  primo Feb 26 at 9:51

PHP — 132 127 125 124 bytes

Basic Monte-Carlo simulation. Every 10M iterations, it prints the current status:

for($i=1,$j=$k=0;;$i++){$x=mt_rand(0,1e7)/1e7;$y=mt_rand(0,1e7)/1e7;$j+=$x*$x+$y*$y<=1;$k++;if(!($i%1e7))echo 4*$j/$k."\n";}

Thanks to cloudfeet and zamnuts for suggestions!

Sample output:

$ php pi.php
3.1410564
3.1414008
3.1413388
3.1412641
3.14132568
3.1413496666667
3.1414522857143
3.1414817
3.1415271111111
3.14155092
...
3.1415901754386
3.1415890482759
3.1415925423731
share|improve this answer
4  
Up for an answer which really computes! –  blabla999 Feb 24 at 22:21
1  
Great answer and approach! –  Jason C Feb 26 at 3:34
    
Don't know about PHP, but in JS you can do something like: $j+=$x*$x+$y*$y<=1; which would save you four bytes. –  cloudfeet Feb 27 at 17:45
1  
Also $k+=1/4; and print $j/$k could be reduced to $k++; and print 4*$j/$k for another byte. –  cloudfeet Feb 27 at 17:50
    
@cloudfeet - Changes made, confirmed code still runs the same. Thank you! –  Yimin Rong Feb 28 at 15:35

J 6

{:*._1

Explanation: *. gives length and angle of a complex number. The angle of -1 is pi. {: takes the tail of the list [length, angle]

Just for the slowly-converging-series-fettishists, for 21 bytes, a Leibniz series:

      +/(4*_1&^%>:@+:)i.1e6
 3.14159
share|improve this answer
9  
In other words, this is atan(0) + pi. I don't think the use of trigonometric functions and pi itself should count as a "calculation". –  Jason C Feb 26 at 3:54
    
@JasonC Arg (that is, argument of a complex number) is not a trigonometric function, despite having values similar to that of arctangent –  mniip Feb 27 at 3:17
    
@mniip Yes, it is. It's just a synonym for atan (well, atan2) on the real and imaginary parts. As you can see there, it is precisely equal, by definition, to atan(0) + pi. –  Jason C Feb 27 at 3:20

Perl, 42 bytes

map{$a+=(-1)**$_/(2*$_+1)}0..9x6;print$a*4

It's calculates π using the Leibniz formula:

Leipniz formula

999999 is used as largest n to get the precision of five decimal digits.

Result: 3.14159165358977

share|improve this answer
    
This is cool! It inspired me to write one in Java 8. –  David Conrad Mar 4 at 18:03

Piet, many codels

Not my answer, but this is the best solution I've seen to this problem:

Pi approximation in Piet

My understanding is that it adds up the pixels in the circle and divides by the radius, and then once again. That is:

A = πr²  # solve for π
π = A/r²
π = (A/r)/r

A better approach in my mind is a program that generates this image at an arbitrary size and then runs it through a Piet interpreter.

Source: http://www.dangermouse.net/esoteric/piet/samples.html

share|improve this answer
    
Could you explain what it actually does? (I know the general idea behind Piet but an explanation on how this particular program work would be a nice addition to your answer). –  plannapus Feb 26 at 9:25
    
I don't really know Piet, but I think this literally measures the area of the red circle and then divides by the radius twice, solving for π = A/(r*r) –  Not that Charles Feb 26 at 13:05
    
Well the area is quite clear, as when the pointer enter the red circle it counts the number of codels in the red area and push it to the stack when exiting (since the exit point is dark red, hence no hue change but one step darker), it's the "dividing by the radius squared" part that I had trouble understanding. –  plannapus Feb 26 at 13:13
1  
@plannapus The radius is "hard-coded" in the dark red line extending from the top-left corner to halfway down the left edge (it's hard to see in the image). Piet is hard to follow but the gist is blocks of color have a value equal to their area (line at left edge has r pixels, circle has area pixels), and the stuff in between is just a bunch of stack and arithmetic operations. Programs start in the top left. The text in the top right is essentially a comment. –  Jason C Feb 26 at 17:19
2  
@JasonC ah of course! The circle touches both upper and lower side so the dark red line descending from the upper side to the exact middle is necessary the radius! Smart! –  plannapus Feb 27 at 7:39

APL - 6

2ׯ1○1

Outputs 3.141592654. It computes twice the arcsine of 1.

A 13-char solution would be:

--/4÷1-2×⍳1e6

This outputs 3.141591654 for me, which fits the requested precision.
It uses the simple + 4/1 - 4/3 + 4/5 - 4/7 ... series to calculate though.

share|improve this answer
1  
Wow, that's one slow convergence! –  Yimin Rong Feb 24 at 21:56
    
My first thought was “why not ¯2○¯1?” (i.e acos -1). But that gives a complex approximation on repl.it (3.1415926425236J¯1.1066193467303274e¯8). Any idea why? Do all implementations do that? –  James Wood Feb 25 at 21:29
    
+1 for your second solution. 2 * asin(1) is a bit of a cheat, though. –  Jason C Feb 26 at 3:56
    
@JamesWood I don't know APL but if I had to guess I'd say it tried to do a sqrt(1-theta^2) (which pops up in a lot of trig identities) at some point and lost some precision somewhere, ending up with a slightly negative 1-theta^2. –  Jason C Feb 26 at 3:59
1  
What's strange is that there's still a tiny imaginary part for acos -0.75. There's no way it could calculate 1 - 0.75 ^ 2 to be negative. –  James Wood Feb 26 at 8:58

J - 5 bytes

|^._1

This means |log(-1)|.

share|improve this answer
    
Clever use of Euler's Identity. –  primo Feb 26 at 9:47
    
Cool, another algebraic identity answer. About as clever as ln(e^(42*pi))/42 or pi*113/113. –  Jason C Feb 26 at 17:03
    
Also works in TI-BASIC –  Timtech Feb 26 at 22:17
1  
(Totally unrelated, I wish we could use LaTeX on codegolf.) –  Jason C Feb 27 at 10:47
1  
(Answer to totally unrelated question, I get by with google charts, for example here.) On topic, this is the sortest answer, and thus should have been accepted. –  primo Feb 27 at 10:51

Google Calculator, 48

stick of butter*(26557.4489*10^-9)/millimeters^3

Takes a stick of butter, does advanced calculations, makes pi out of it. I figured since everyone else was doing simple math answers I would add a slightly more unique one.

Example

share|improve this answer
2  
The stick of butter is cute and funny but this is essentially yet another pi*x/x+y-y algebraic identity. –  Jason C Feb 26 at 17:24
7  
There are so many better ways to make pi using a stick of butter –  Not that Charles Feb 26 at 20:24

Octave, 31

quad(inline("sqrt(4-x^2)"),0,2)

Calculates the area of one quarter of a circle with radius 2, through numerical integration.

octave:1> quad(inline("sqrt(4-x^2)"),0,2)
ans =     3.14159265358979
share|improve this answer
1  
Nice! +1 when my votes recharge. –  Jason C Feb 26 at 20:38

TECHNICALLY I'M CALCULATING, 9

0+3.14159

TECHNICALLY I'M STILL CALCULATING, 10

PI-acos(1)

I'M CALCULATING SO HARD, 8

acos(-1)

I ACCIDENTALLY PI, 12

"3.14"+"159"

And technically, this answer stinks.

share|improve this answer
21  
So header, much big title, very pain for my eyes, wow. –  Pierre Arlaud Feb 26 at 9:45
1  
pluzz wan for much lulz, thankz –  Jonathan Van Matre Feb 26 at 19:14
    
Hey baby, wanna expand my Taylor series? –  Jason C Feb 26 at 19:26
1  
    
@SimonT You didn't answer my question about the Taylor series. But while you're thinking about it, see my comments on the question and most of the other answers here. :P –  Jason C Feb 27 at 5:23

Mathematica 6

180N@° 
-->3.14159
share|improve this answer

Python, 88

Solution :

l=q=d=0;t,s,n,r=3.,3,1,24
while s!=l:l,n,q,d,r=s,n+q,q+8,d+r,r+32;t=(t*n)/d;s+=t
print s

Sample output in Python shell :

>>> print s
3.14159265359

Manages to avoid any imports. Can easily be swapped to use the arbitrary precision Decimal library; just replace 3. with Decimal('3'), set the precision before and after, then unary plus the result to convert precision.

And unlike a whole lot of the answers here, actually computes π instead of relying on built-in constants or math fakery, i.e. math.acos(-1), math.radians(180), etc.

share|improve this answer

x86 assembly language (5 characters)

fldpi

Whether this loads a constant from ROM or actually calculates the answer depends on the processor though (but on at least some, it actually does a calculation, not just loading the number from ROM). To put things in perspective, it's listed as taking 40 clock cycles on a 387, which is rather more than seems to make sense if it were just loading the value from ROM.

If you really want to ensure a calculation you could do something like:

fld1
fld1
fpatan
fimul f

f dd 4

[for 27 characters]

share|improve this answer
    
Can you explain, please ? –  Nicolas Barbulesco Feb 25 at 20:16
    
And, on some processors, what calculcation would fldpi do ? –  Nicolas Barbulesco Feb 25 at 20:22
1  
I don't think using a command that loads pi (or even computes it based on somebody else's asin implementation or any existing trig function implementations at all) really counts in the spirit of "calculating" anything (the "omg assembler" factor doesn't really change that). Perhaps port this to the shortest assembler implementation possible, and it can be called a "calculation". –  Jason C Feb 26 at 4:07
2  
@JasonC: Sounds like an entirely arbitrary notion to me, with no more real sense than my deciding that people had to implement addition, subtraction, multiplication and division on their own if they're doing to use them. –  Jerry Coffin Feb 26 at 4:50
2  
@JerryCoffin Instead of arguing technicalities, suffice it to say that neither asin(-1) nor fldpi are particularly interesting or creative. There's not much purpose in competing to see whose favorite language has the shortest name for predefined trig functions and pi constants. –  Jason C Feb 26 at 5:04

python - 47 45

pi is actually being calculated without trig functions or constants.

a=4
for i in range(9**6):a-=(-1)**i*4/(2*i+3)

result:

>>> a
3.1415907719167966
share|improve this answer
    
Should be able to save a byte by dropping the zero after the decimal place for forced float interpretation. :) Bonus points for brevity, but I like mine for arbitrary accuracy and lower memory utilization. (Edited to scratch the parenthesis idea; I see what's going on there and my isolated test didn't catch the issue.) –  amcgregor Feb 26 at 5:28
    
Uh… no. After your modification this no longer gives valid output. (265723 ≭ π) You still need the period, just not the trailing zero. –  amcgregor Feb 27 at 21:05
    
@amcgregor use python 3? –  qwr Feb 27 at 21:13
    
I do, though I primarily develop under 2.7 and make my code work in both. However on the stock Mac 10.9 python3 installation your code causes a segmentation fault. –  amcgregor Feb 28 at 1:00
    
@amcgregor I just tested it, it works for me (python 3.3.4) –  qwr Feb 28 at 1:08

Python, Riemann zeta (58 char)

import math
math.sqrt(6*sum(n**-2 for n in range(1,9**9)))

Or spare two characters, but use scipy

import scipy.special as s, math
math.sqrt(6*s.zeta(2,1))
share|improve this answer

C, 99

Directly computes area / r^2 of a circle.

double p(n,x,y,r){r=10000;for(n=x=0;x<r;++x)for(y=1;y<r;++y)n+=x*x+y*y<=r*r;return(double)n*4/r/r;}

This function will calculate pi by counting the number of pixels in a circle of radius r then dividing by r*r (actually it just calculates one quadrant). With r as 10000, it is accurate to 5 decimal places (3.1415904800). The parameters to the function are ignored, I just declared them there to save space.

share|improve this answer

Javascript, 43 36

x=0;for(i=1;i<1e6;i++){x+=1/i/i};Math.sqrt(6*x)

x becomes zeta(2)=pi^2/6 so sqrt(6*x)=pi. (47 characters)

After using the distributive property and deleting the curly brackets from the for loop you get:

x=0;for(i=1;i<1e6;i++)x+=6/i/i;Math.sqrt(x)

(43 characters)

It returns:

3.14159169865946

Edit:

I found an even shorter way using the Wallis product:

x=i=2;for(;i<1e6;i+=2)x*=i*i/(i*i-1)

(36 characters)

It returns:

3.141591082792245
share|improve this answer

bc -l, 37 bytes

for(p=n=2;n<7^7;n+=2)p*=n*n/(n*n-1);p

I don't see any other answers using the Wallis product, so since its named after my namesake (my History of Mathematics lecturer got a big kick out of that), I couldn't resist.

Turns out its a fairly nice algorithm from the golfing perspective, but its rate of convergence is abysmal - approaching 1 million iterations just to get 5 decimal places:

$ time bc -l<<<'for(p=n=2;n<7^7;n+=2)p*=n*n/(n*n-1);p'
3.14159074622629555058

real    0m3.145s
user    0m1.548s
sys 0m0.000s
$ 

bc -l, 15 bytes

Alternatively, we can use Newton-Raphson to solve sin(x)=0, with a starting approximation of 3. Because this converges in so few iterations, we simply hard-code 2 iterations, which gives 10 decimal places:

x=3+s(3);x+s(x)

The iterative formula according to Newton-Raphson is:

x[n+1] = x[n] - ( sin(x[n]) / sin'(x[n]) )

sin' === cos and cos(pi) === -1, so we simply approximate the cos term to get:

x[n+1] = x[n] + sin(x[n])

Output:

$ bc -l<<<'x=3+s(3);x+s(x)'
3.14159265357219555873
$ 
share|improve this answer
    
+1 now that's more like it! –  Jason C Feb 27 at 1:51
    
@JasonC What is your opinion of application of Newton-Raphson to solve sin(x)=0 (see edit)? –  DigitalTrauma Apr 13 at 17:56

Javascript: 99 characters

Using the formula given by Simon Plouffe in 1996, this works with 6 digits of precision after the decimal point:

function f(k){return k<2?1:f(k-1)*k}for(y=-3,n=1;n<91;n++)y+=n*(2<<(n-1))*f(n)*f(n)/f(2*n);alert(y)

This longer variant (130 characters) has a better precision, 15 digits after the decimal point:

function e(x){return x<1?1:2*e(x-1)}function f(k){return k<2?1:f(k-1)*k}for(y=-3,n=1;n<91;n++)y+=n*e(n)*f(n)*f(n)/f(2*n);alert(y)

I made this based in my two answers to this question.

share|improve this answer

Ruby, 54 50 49

p (0..9**6).map{|e|(-1.0)**e/(2*e+1)*4}.reduce :+

Online Version for testing.

Another version without creating an array (50 chars):

x=0;(0..9**6).each{|e|x+=(-1.0)**e/(2*e+1)*4}; p x

Online Version for testing.

share|improve this answer
    
It's interesting to see the language differences that such compact solutions can give. For example, the Python translation of the above is 105 characters (after using some trivial code compression tricks): a=__import__;reduce(a('operator').__add__,a('itertools').imap(lambda e:(-1.0)**e/(2*e+1)*4,xrange(9**6))) -- note the use of xrange/imap; in Python 3 you can avoid this; basically I don't want all of your RAM to get consumed constructing a list with so many entries. –  amcgregor Feb 25 at 21:18
1  
You're absolutely right. It is often very convenient to use (especially Ruby's) Array and Enumerable functions, though it might really not be the best idea in terms of performance and speed... Well, thinking about that, it should be possible to do the calculation with the Range.each method instead of creating a map. –  David Herrmann Feb 25 at 21:30
    
Yes, it's possible - just one character more... –  David Herrmann Feb 25 at 21:35
    
Your first answer is not as precise as your second. –  Josh Mar 1 at 18:50
    
Could you elaborate, please? Same algorithm, same output for me? –  David Herrmann Mar 1 at 19:49

TI CAS, 35

lim(x*(1/(tan((180-360/x)/2))),x,∞)
share|improve this answer

Perl - 35 bytes

$\=$\/(2*$_-1)*$_+2for-46..-1;print

Produces full floating point precision. A derivation of the formula used can be seen elsewhere.

Sample usage:

$ perl pi.pl
3.14159265358979

Arbitrary Precision Version

use bignum a,99;$\=$\/(2*$_-1)*$_+2for-329..-1;print

Extend as needed. The length of the iteration (e.g. -329..-1) should be adjusted to be approximately log2(10)3.322 times the number of digits.

3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211707

Or, using bigint instead:

use bigint;$\=$\/(2*$_-1)*$_+2e99for-329..-1;print

This runs noticably faster, but doesn't include a decimal point.

3141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067
share|improve this answer

C# 192

class P{static void Main(){var s=(new System.Net.WebClient()).DownloadString("http://www.ctan.org/pkg/tex");System.Console.WriteLine(s.Substring(s.IndexOf("Ver&shy;sion")+21).Split(' ')[0]);}}

Outputs:

3.14159265

No math involved. Just looks up the current version of TeX and does some primitive parsing of the resulting html. Eventually it will become π according to Wikipedia.

share|improve this answer

Python 3 Monte Carlo (103 char)

from random import random as r
sum(1 for x,y in ((r(),r()) for i in range(2**99)) if x**2+y**2<1)/2**97
share|improve this answer

Game Maker Language, 34

Assumes all uninitialized variables as 0. This is default in some versions of Game Maker.

for(i=1;i<1e8;i++)x+=6/i/i;sqrt(x)

Result:

3.14159169865946
share|improve this answer
    
very nice. also, in C float k(){double x=0,i=0;for(;i++<999999;)x+=6/i/i;return sqrt(x);} is shorter than this one –  izabera Mar 1 at 11:04
    
even shorter with 1e8 instead of 999999 –  izabera Mar 1 at 11:12
    
@izabera True, thanks. –  Timtech Mar 1 at 23:57

Java - 83 55

Shorter version thanks to Navin.

class P{static{System.out.print(Math.toRadians(180));}}

Old version:

class P{public static void main(String[]a){System.out.print(Math.toRadians(180));}}
share|improve this answer
    
This doesn't do any calculation. –  hosch250 Feb 24 at 22:09
    
I don't understand the downvote, although - I'd answered with "Math.toRadians(180)". It is also questionable, who computes pi: the compiler or the program. But that was not part of the question. –  blabla999 Feb 24 at 22:11
2  
@user2509848 It most certainly does: it multiplies 180 by pi/180. –  AJMansfield Feb 24 at 23:15
    
You mean it multiplies pi by 1? It is essentially the same thing. I did not downvote it, but I don't think it really counts. –  hosch250 Feb 24 at 23:17
1  
Can be shorter: codegolf.stackexchange.com/a/22057/14610 –  Navin Feb 25 at 14:25

Ruby, 82

q=1.0
i=0
(0.0..72).step(8){|k|i+=1/q*(4/(k+1)-2/(k+4)-1/(k+5)-1/(k+6))
q*=16}
p i

Uses some formula I don't really understand and just copied down. :P

Output: 3.1415926535897913

share|improve this answer

JavaScript - 19 bytes

Math.pow(29809,1/9)

Calculates the 9th root of 29809.

3.1415914903890925
share|improve this answer

R: 33 characters

sqrt(8*sum(1/seq(1,1000001,2)^2))
[1] 3.141592

Hopefully this follows the rules.

share|improve this answer

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
share|improve this answer

protected by Community Feb 28 at 8:17

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.