# 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

## 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

• mhmh - that is actually a polyglot answer. Works in Smalltalk too! – blabla999 Feb 24 '14 at 22:02
• Blasphemy! It's barely a calculation! – mniip Feb 24 '14 at 22:08
• well, it is a division, and it's precision satisfies the requirement... (and even the bible is less accurate; you would not label that blasphemy - would you? 3* ;-) – blabla999 Feb 24 '14 at 22:15
• The awkward moment when I wrote this as a serious answer but everyone interprets it as a joke... – user12205 Feb 25 '14 at 19:50
• Highest voted answer: 355/113. Lowest voted answer: 3+.14159. I don't see much difference, really. – primo Feb 26 '14 at 9:51

# PHP — 132127125 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

• Up for an answer which really computes! – blabla999 Feb 24 '14 at 22:21
• 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 '14 at 17:45 • Also $k+=1/4; and print $j/$k could be reduced to $k++; and print 4*$j/$k for another byte. – cloudfeet Feb 27 '14 at 17:50 • @cloudfeet - Changes made, confirmed code still runs the same. Thank you! – user15259 Feb 28 '14 at 15:35 • @MarkC - Conceptually it is throwing darts randomly in a rectangle 0,0 to 1,1. Those less than or equal to distance 1 from 0,0 are considered inside, else outside. The shape of this distance 1 happens to be a quarter circle or π/4. The [number of darts inside the quarter circle] / [total number of darts] will approximate π/4 as the number of samples increases. – user15259 Apr 13 '17 at 2:58 ## 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  • 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 '14 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 '14 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 '14 at 3:20 ## Perl, 42 bytes map{$a+=(-1)**$_/(2*$_+1)}0..9x6;print$a*4  It's calculates π using the Leibniz formula: 999999 is used as largest n to get the precision of five decimal digits. Result: 3.14159165358977 • This is cool! It inspired me to write one in Java 8. – David Conrad Mar 4 '14 at 18:03 ## Piet, many codels Not my answer, but this is the best solution I've seen to this problem: 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. • 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 '14 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 '14 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 '14 at 13:13 • @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 '14 at 17:19 • @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 '14 at 7:39 # 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. • So header, much big title, very pain for my eyes, wow. – Pierre Arlaud Feb 26 '14 at 9:45 • pluzz wan for much lulz, thankz – Jonathan Van Matre Feb 26 '14 at 19:14 • Hey baby, wanna expand my Taylor series? – Jason C Feb 26 '14 at 19:26 • meta.codegolf.stackexchange.com/questions/1061/… – SimonT Feb 27 '14 at 4:54 • @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 '14 at 5:23 # 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. • Wow, that's one slow convergence! – user15259 Feb 24 '14 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 '14 at 21:29 • +1 for your second solution. 2 * asin(1) is a bit of a cheat, though. – Jason C Feb 26 '14 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 '14 at 3:59 • 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 '14 at 8:58 # J - 5 bytes |^._1  This means |log(-1)|. • Clever use of Euler's Identity. – primo Feb 26 '14 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 '14 at 17:03 • Also works in TI-BASIC – Timtech Feb 26 '14 at 22:17 • (Totally unrelated, I wish we could use LaTeX on codegolf.) – Jason C Feb 27 '14 at 10:47 • (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 '14 at 10:51 # 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  • Nice! +1 when my votes recharge. – Jason C Feb 26 '14 at 20:38 # Mathematica 6 180N@° -->3.14159  # 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. ### 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] • Can you explain, please ? – Nicolas Barbulesco Feb 25 '14 at 20:16 • And, on some processors, what calculcation would fldpi do ? – Nicolas Barbulesco Feb 25 '14 at 20:22 • 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 '14 at 4:07 • @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 '14 at 4:50 • @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 '14 at 5:04 # 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
$ • +1 now that's more like it! – Jason C Feb 27 '14 at 1:51 • @JasonC What is your opinion of application of Newton-Raphson to solve sin(x)=0 (see edit)? – Digital Trauma Apr 13 '14 at 17:56 ## 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


# 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

• 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 '14 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 '14 at 21:05
• @amcgregor use python 3? – qwr Feb 27 '14 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 '14 at 1:00
• @amcgregor I just tested it, it works for me (python 3.3.4) – qwr Feb 28 '14 at 1:08

# 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.

# 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


## Python, Riemann zeta (58 41 char)

(6*sum(n**-2for n in range(1,9**9)))**0.5


Or spare two characters, but use scipy

import scipy.special as s
(6*s.zeta(2,1))**0.5


Edit: Saved 16 (!) characters thanks to amcgregor

• Can potentially avoid the math import and sqrt call by pivoting to exponentiation instead: (6*sum(n**-2 for n in range(1,9**9)))**0.5 – amcgregor Jun 21 '19 at 13:41

## 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)


### Ruby, 5450 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.

• 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 '14 at 21:18
• 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 '14 at 21:30
• Yes, it's possible - just one character more... – David Herrmann Feb 25 '14 at 21:35
• Your first answer is not as precise as your second. – Josh Mar 1 '14 at 18:50
• Could you elaborate, please? Same algorithm, same output for me? – David Herrmann Mar 1 '14 at 19:49

## TI CAS, 35

lim(x*(1/(tan((180-360/x)/2))),x,∞)

• I looked back at this and i completely forget how it works :P – TheDoctor Nov 9 '14 at 0:06

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.

## 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


## 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

• 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 '14 at 11:04
• even shorter with 1e8 instead of 999999 – izabera Mar 1 '14 at 11:12
• Could you use for(i=1;i<1e8;)x+=6/i/i++;sqrt(x) to save a byte (or alternatively for(i=1;i++<1e8;))? – mbomb007 Jan 14 '15 at 15:37
• @mbomb007 Unfortunately not, GML requires all 3 parameters. – Timtech Jan 15 '15 at 2:07

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));}}

• This doesn't do any calculation. – user10766 Feb 24 '14 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 '14 at 22:11
• @user2509848 It most certainly does: it multiplies 180 by pi/180. – AJMansfield Feb 24 '14 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. – user10766 Feb 24 '14 at 23:17
• Can be shorter: codegolf.stackexchange.com/a/22057/14610 – Navin Feb 25 '14 at 14:25

## R: 33 characters

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


Hopefully this follows the rules.

# 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

# Ruby, 12

p 1.570796*2


I am technically "calculating" pi an approximation of pi.

• No, you are not technically calculating pi. You are technically calculating 3.141592, which happens to be close to pi, but will never converge to exactly acos(-1). – wchargin Feb 25 '14 at 2:38
• @Wchar Ok, edited – Doorknob Feb 25 '14 at 2:42
• I don't think hard-coding pi/2 then multiplying it by 2 really counts; the point is to calculate pi, not obfuscate a numeric literal. – Jason C Feb 26 '14 at 3:40

## JavaScript - 19 bytes

Math.pow(29809,1/9)


Calculates the 9th root of 29809.

3.1415914903890925


## 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))