17
\$\begingroup\$

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.

\$\endgroup\$
37
  • 5
    \$\begingroup\$ @hvd Why do you think it should be disqualified? It fits the specs ... \$\endgroup\$ Feb 24, 2014 at 21:53
  • 5
    \$\begingroup\$ @hvd acos(-1). I win! \$\endgroup\$ Feb 24, 2014 at 23:47
  • 4
    \$\begingroup\$ 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. \$\endgroup\$ Feb 25, 2014 at 20:07
  • 7
    \$\begingroup\$ 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. \$\endgroup\$
    – Cruncher
    Feb 25, 2014 at 21:54
  • 8
    \$\begingroup\$ To make this question interesting it needs a scoring function that rewards digits of pi per byte of code. \$\endgroup\$ Feb 26, 2014 at 5:16

67 Answers 67

58
\$\begingroup\$

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

\$\endgroup\$
25
  • 14
    \$\begingroup\$ mhmh - that is actually a polyglot answer. Works in Smalltalk too! \$\endgroup\$
    – blabla999
    Feb 24, 2014 at 22:02
  • 7
    \$\begingroup\$ Blasphemy! It's barely a calculation! \$\endgroup\$
    – mniip
    Feb 24, 2014 at 22:08
  • 3
    \$\begingroup\$ 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* ;-) \$\endgroup\$
    – blabla999
    Feb 24, 2014 at 22:15
  • 30
    \$\begingroup\$ The awkward moment when I wrote this as a serious answer but everyone interprets it as a joke... \$\endgroup\$
    – user12205
    Feb 25, 2014 at 19:50
  • 22
    \$\begingroup\$ Highest voted answer: 355/113. Lowest voted answer: 3+.14159. I don't see much difference, really. \$\endgroup\$
    – primo
    Feb 26, 2014 at 9:51
50
\$\begingroup\$

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
\$\endgroup\$
8
  • 5
    \$\begingroup\$ Up for an answer which really computes! \$\endgroup\$
    – blabla999
    Feb 24, 2014 at 22:21
  • \$\begingroup\$ 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. \$\endgroup\$
    – cloudfeet
    Feb 27, 2014 at 17:45
  • 1
    \$\begingroup\$ Also $k+=1/4; and print $j/$k could be reduced to $k++; and print 4*$j/$k for another byte. \$\endgroup\$
    – cloudfeet
    Feb 27, 2014 at 17:50
  • \$\begingroup\$ @cloudfeet - Changes made, confirmed code still runs the same. Thank you! \$\endgroup\$
    – user15259
    Feb 28, 2014 at 15:35
  • 2
    \$\begingroup\$ @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. \$\endgroup\$
    – user15259
    Apr 13, 2017 at 2:58
32
\$\begingroup\$

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
\$\endgroup\$
3
  • 12
    \$\begingroup\$ 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". \$\endgroup\$
    – Jason C
    Feb 26, 2014 at 3:54
  • \$\begingroup\$ @JasonC Arg (that is, argument of a complex number) is not a trigonometric function, despite having values similar to that of arctangent \$\endgroup\$
    – mniip
    Feb 27, 2014 at 3:17
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Jason C
    Feb 27, 2014 at 3:20
25
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ This is cool! It inspired me to write one in Java 8. \$\endgroup\$ Mar 4, 2014 at 18:03
20
\$\begingroup\$

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.

\$\endgroup\$
6
  • 31
    \$\begingroup\$ So header, much big title, very pain for my eyes, wow. \$\endgroup\$ Feb 26, 2014 at 9:45
  • 1
    \$\begingroup\$ pluzz wan for much lulz, thankz \$\endgroup\$ Feb 26, 2014 at 19:14
  • \$\begingroup\$ Hey baby, wanna expand my Taylor series? \$\endgroup\$
    – Jason C
    Feb 26, 2014 at 19:26
  • 1
    \$\begingroup\$ meta.codegolf.stackexchange.com/questions/1061/… \$\endgroup\$
    – SimonT
    Feb 27, 2014 at 4:54
  • \$\begingroup\$ @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 \$\endgroup\$
    – Jason C
    Feb 27, 2014 at 5:23
19
\$\begingroup\$

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

\$\endgroup\$
7
  • \$\begingroup\$ 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). \$\endgroup\$
    – plannapus
    Feb 26, 2014 at 9:25
  • \$\begingroup\$ 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) \$\endgroup\$ Feb 26, 2014 at 13:05
  • \$\begingroup\$ 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. \$\endgroup\$
    – plannapus
    Feb 26, 2014 at 13:13
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Jason C
    Feb 26, 2014 at 17:19
  • 2
    \$\begingroup\$ @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! \$\endgroup\$
    – plannapus
    Feb 27, 2014 at 7:39
14
\$\begingroup\$

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.

\$\endgroup\$
7
  • 1
    \$\begingroup\$ Wow, that's one slow convergence! \$\endgroup\$
    – user15259
    Feb 24, 2014 at 21:56
  • \$\begingroup\$ 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? \$\endgroup\$
    – mudri
    Feb 25, 2014 at 21:29
  • \$\begingroup\$ +1 for your second solution. 2 * asin(1) is a bit of a cheat, though. \$\endgroup\$
    – Jason C
    Feb 26, 2014 at 3:56
  • \$\begingroup\$ @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. \$\endgroup\$
    – Jason C
    Feb 26, 2014 at 3:59
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – mudri
    Feb 26, 2014 at 8:58
14
\$\begingroup\$

J - 5 bytes

|^._1

This means |log(-1)|.

\$\endgroup\$
12
  • \$\begingroup\$ Clever use of Euler's Identity. \$\endgroup\$
    – primo
    Feb 26, 2014 at 9:47
  • 1
    \$\begingroup\$ Cool, another algebraic identity answer. About as clever as ln(e^(42*pi))/42 or pi*113/113. \$\endgroup\$
    – Jason C
    Feb 26, 2014 at 17:03
  • \$\begingroup\$ Also works in TI-BASIC \$\endgroup\$
    – Timtech
    Feb 26, 2014 at 22:17
  • 1
    \$\begingroup\$ (Totally unrelated, I wish we could use LaTeX on codegolf.) \$\endgroup\$
    – Jason C
    Feb 27, 2014 at 10:47
  • 1
    \$\begingroup\$ (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. \$\endgroup\$
    – primo
    Feb 27, 2014 at 10:51
12
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Nice! +1 when my votes recharge. \$\endgroup\$
    – Jason C
    Feb 26, 2014 at 20:38
11
\$\begingroup\$

Mathematica 6

180N@° 
-->3.14159
\$\endgroup\$
11
\$\begingroup\$

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.

\$\endgroup\$
9
\$\begingroup\$

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]

\$\endgroup\$
8
  • 1
    \$\begingroup\$ Can you explain, please ? \$\endgroup\$ Feb 25, 2014 at 20:16
  • \$\begingroup\$ And, on some processors, what calculcation would fldpi do ? \$\endgroup\$ Feb 25, 2014 at 20:22
  • 1
    \$\begingroup\$ 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". \$\endgroup\$
    – Jason C
    Feb 26, 2014 at 4:07
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ Feb 26, 2014 at 4:50
  • 3
    \$\begingroup\$ @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. \$\endgroup\$
    – Jason C
    Feb 26, 2014 at 5:04
8
\$\begingroup\$

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
$ 
\$\endgroup\$
2
  • \$\begingroup\$ +1 now that's more like it! \$\endgroup\$
    – Jason C
    Feb 27, 2014 at 1:51
  • \$\begingroup\$ @JasonC What is your opinion of application of Newton-Raphson to solve sin(x)=0 (see edit)? \$\endgroup\$ Apr 13, 2014 at 17:56
6
\$\begingroup\$

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
\$\endgroup\$
6
\$\begingroup\$

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
\$\endgroup\$
5
  • \$\begingroup\$ 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.) \$\endgroup\$
    – amcgregor
    Feb 26, 2014 at 5:28
  • \$\begingroup\$ Uh… no. After your modification this no longer gives valid output. (265723 ≭ π) You still need the period, just not the trailing zero. \$\endgroup\$
    – amcgregor
    Feb 27, 2014 at 21:05
  • \$\begingroup\$ @amcgregor use python 3? \$\endgroup\$
    – qwr
    Feb 27, 2014 at 21:13
  • \$\begingroup\$ 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. \$\endgroup\$
    – amcgregor
    Feb 28, 2014 at 1:00
  • \$\begingroup\$ @amcgregor I just tested it, it works for me (python 3.3.4) \$\endgroup\$
    – qwr
    Feb 28, 2014 at 1:08
6
\$\begingroup\$

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.

\$\endgroup\$
6
\$\begingroup\$

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
\$\endgroup\$
6
\$\begingroup\$

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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 \$\endgroup\$
    – amcgregor
    Jun 21, 2019 at 13:41
5
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

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.

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

TI CAS, 35

lim(x*(1/(tan((180-360/x)/2))),x,∞)
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I looked back at this and i completely forget how it works :P \$\endgroup\$
    – TheDoctor
    Nov 9, 2014 at 0:06
5
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ I'm 5 years late, but this is a standard loophole that was created 4 days before this answer. \$\endgroup\$ Jun 22, 2019 at 17:53
5
\$\begingroup\$

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
\$\endgroup\$
5
\$\begingroup\$

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
\$\endgroup\$
4
  • \$\begingroup\$ 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 \$\endgroup\$
    – izabera
    Mar 1, 2014 at 11:04
  • \$\begingroup\$ even shorter with 1e8 instead of 999999 \$\endgroup\$
    – izabera
    Mar 1, 2014 at 11:12
  • \$\begingroup\$ 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;))? \$\endgroup\$
    – mbomb007
    Jan 14, 2015 at 15:37
  • \$\begingroup\$ @mbomb007 Unfortunately not, GML requires all 3 parameters. \$\endgroup\$
    – Timtech
    Jan 15, 2015 at 2:07
4
\$\begingroup\$

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));}}
\$\endgroup\$
6
  • \$\begingroup\$ This doesn't do any calculation. \$\endgroup\$
    – user10766
    Feb 24, 2014 at 22:09
  • \$\begingroup\$ 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. \$\endgroup\$
    – blabla999
    Feb 24, 2014 at 22:11
  • 2
    \$\begingroup\$ @user2509848 It most certainly does: it multiplies 180 by pi/180. \$\endgroup\$ Feb 24, 2014 at 23:15
  • \$\begingroup\$ 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. \$\endgroup\$
    – user10766
    Feb 24, 2014 at 23:17
  • 1
    \$\begingroup\$ Can be shorter: codegolf.stackexchange.com/a/22057/14610 \$\endgroup\$
    – Navin
    Feb 25, 2014 at 14:25
4
\$\begingroup\$

R: 33 characters

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

Hopefully this follows the rules.

\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

Ruby, 12

p 1.570796*2

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

\$\endgroup\$
3
  • \$\begingroup\$ 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). \$\endgroup\$
    – wchargin
    Feb 25, 2014 at 2:38
  • \$\begingroup\$ @Wchar Ok, edited \$\endgroup\$
    – Doorknob
    Feb 25, 2014 at 2:42
  • 3
    \$\begingroup\$ 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. \$\endgroup\$
    – Jason C
    Feb 26, 2014 at 3:40
3
\$\begingroup\$

JavaScript - 19 bytes

Math.pow(29809,1/9)

Calculates the 9th root of 29809.

3.1415914903890925
\$\endgroup\$
3
\$\begingroup\$

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))
\$\endgroup\$

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