We’re rewarding the question askers & reputations are being recalculated! Read more.

Hot answers tagged

128

C + x86 assembly Not satisfied with a constant defined in the software of your language? Why not use a language that can access a constant value of PI right from your FPU hardware: #include <stdio.h> int main (int argc, char **argv) { double pi; __asm__("fldpi" : "=t" (pi)); printf("%g\n", 3 * 3 * pi); return (0); }


113

PHP - 22 bytes <?=date('n.j',8899e5); Pi Day in year 1998 was really cool!


92

C, 39 Assumes the machine is little-endian and uses IEEE floating-point standard. main(){printf("%.2f",*(float*)"P@I@");} The fun fact is that "P@I@" is actually not related to PI but is equivalent to 0x40494050 which is the representation of 3.144550323486328 http://ideone.com/uXVEtl


90

MATL, 70 68 67 bytes '()'12:)l10:&<toYP43Y$51hb(!10Xy'\::\'FFhZ++'|'3$Yc'||\'3:(95'Zd'o( Try it online! Explanation What a mess. But hey, there's a convolution! The explanation will be clearer if you can inspect the stack contents after a given statement. To do it, just insert X#0$% at that point. (This means: X# show stack contents, 0$ don't ...


77

Python, bash, C, J, PHP and Python3 import subprocess p = subprocess.Popen(""" echo ' #define _USE_MATH_DEFINES #include <stdio.h> #include <math.h> int main(int pi) { if (pi == 1) printf("%.5f", M_PI); if (pi == 2) printf("o. 1"); if (pi == 3) printf("<?php printf(\\"%%.5f\\", pi()); ?>"); if (pi == 4) printf("import ...


77

Algorithm Using the well-known result: we define in Python 3: from math import sin from functools import reduce from operator import mul def integrate(f, a, b, n): h = (b-a)/n i = h * sum(f(a+i*h+h/2) for i in range(n)) return i def sinc(x): return sin(x)/x def borwein(n): def f(x): g = lambda i: sinc(x/(2*i+1)) return reduce(...


59

To find pi, we will integrate this well known differential equation: With an initial condition It is well known that this initial value problem converges to π as t increases without bound. So, all we need is to start with a reasonable guess for something between 0 and 2π, and we can perform numerical integration. 3 is close to π, so we will pick y = 3 to ...


57

JavaScript alert(Math.atan2(0, -0) - Math.atan2(-0, -0) + Math.atan2(0, 0)) Help, I'm trapped in a universe factory, and I'm not sure what I'm doing. Math.atan2 is supposed to return pi with good values, right? Math.atan2(0, -0) returns pi, so if I subtract it, and add it, I should still have pi.


56

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


50

dc, 11 9 bytes zE[.]znPp z Push current stack depth (0) onto the stack E Push E16 (==1410) [.] Push the string "." z Push current stack depth (3) onto the stack n Pop 3 and print as number P Pop "." and print as char p Pop 14 and print as number with newline Output: $ dc <<< zE[.]znPp 3.14 $


42

JavaScript (ES5) 20 bytes A variation of m.buettner's JS solution. (x='.'+0xE).length+x Edit: JavaScript (ES5) 18 bytes A variation of ComFreek's idea of using the base64 decode function. atob('Mw')+'.'+0xE Edit: Javascript (ES5) 16 bytes If the unary + operator is allowed to cast a string to a number, it can be reduced to: +atob('MDMuMTQ')


41

PHP/MYSQL $link = mysqli_connect("localhost", "user", "password", "dbname"); $query = mysqli_query($link, 'SELECT PI() AS pi'); $row = mysqli_fetch_assoc($query); echo 3*3*$row['pi'];


40

BASIC (More specifically, Chipmunk Basic) This uses an infinite series discovered by Nilakantha Somayaji in the 15th century: ' Calculate pi using the Nilakantha series: ' 4 4 4 4 ' pi = 3 + ----- - ----- + ----- - ------ + ... ' 2x3x4 4x5x6 6x7x8 8x9x10 i = pi = 0 numerator = -4 while i<10000 i = ...


39

Haskell, 41 bytes When is pi day in Australia? p=(\(a:n:y:t:i:m:e:_)->[m,a,t,e])['.'..] Edited to add: like the other Haskell answer, that outputs a string, so has quotes. You can score 33, and be strictly within the rules, but it's less fun: p=putStr$map([','..]!!)[7,2,5,8]


37

Perl, 93 bytes $_=bpi$=;printf'()'x6x!$`.' %12s',F.ee x!$\--^substr"\32::\\$&|",-12while/.{$\}/g Requires the command line option -l71Mbignum=bpi, counted as 14. The \32 should be replaced by a literal character 26. Sample Usage $ perl -l71Mbignum=bpi pi-slice.pl ()()()()()() |\3.1415926| |:\53589793| \::\2384626| \::\433832| \::\79502| \::\...


34

Perl/Tk with C, Pascal, Java, JavaScript, LaTeX3, Prolog, Perl, Scheme, Lua, Python, TeX/PGF The following Perl script displays a windows that lists the values of π and the calculated area. The value of π is taken from different languages as shown below. The one-file script: #!/usr/bin/env perl use strict; $^W=1; use Tk; use Tk::Font; use Tk::...


32

Morse Code, 33 Bytes morse -d ...-- .-.-.- .---- ....- Technically speaking, the information only takes 21 bytes.


31

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


30

Emotinomicon, 48 bytes / 13 characters I do it, not because it is short, but because it is fun. Try it here. You'll have to copy+paste it into the textbox. 😼⏪🆙😦✖😎😿➕😨😼🆙😄⏩ Explanation: 😼 ⏪ 🆙 😦 ✖ 😎 😿 ➕ 😼 🆙 😄 ⏩ explanation 😼 take numeric input ⏪ ...


27

J - 15 11 10 char Made it shorter, using the fantastic i:. 6{i:6.28j8 Explained: 6.28j8 - The complex number 6.28 + 8i. i: - This is where the magic happens. i: on a complex number A+Bi, B≠0 takes B+1 equally spaced points from the interval [-A,A]. 6{ - Take element at index 6, which just so happens to be 3.14. Previously, we had the following ...


25

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


25

CJam - 8 6 S`,'.E CJam is a new language I am developing, similar to GolfScript - http://sf.net/p/cjam. Here is the explanation: S is a variable preinitialized to space (" ") ` generates the string representation of the last value - which is exactly " " (3 characters) , calculates the string length (3) '. is the dot character E is a variable ...


25

JavaScript (ES6), 187 174 bytes This is 1 byte shorter than just displaying the plain text. for(y=n=0,s=`()()()()()() `;y<10;y++,s+=`| `)for(x=-2;x++<9;)s+=x>y?(Math.PI+'2384626433832795028841971693')[n++]:`\\${y>8?'__':x+1|y>2?'::':'||'}\\`[y-x]||' ';console.log(s)


23

Golfscript, 71 70 69 chars 2\!:^2^..292^15.2/3]{(.)2/.9>+{\+.((}*;.}do;;]-1%{^0@{2$*+\}/"/"\n}/; (Assumes that you don't pass it anything on stdin) I don't want to hear any more whinging by people who don't have built-in constants for pi. I don't even have floating point numbers! See http://en.wikipedia.org/wiki/Continued_fraction#...


22

05AB1E, 3 bytes žs¤ Explained žs # push pi to N digits ¤ # get last digit Try it online Uses 1-based indexing. Supports up to 100k digits.


22

Python 2, 69 75 71 67 bytes Saved 4 bytes due to caird coinheringaahing. x=p=1333 while~-p:x=p/2*x/p+2*10**200;p-=2 print`x`.find(input(),1) Not finding 3 at position zero cost 6 2 bytes. Input is given as a string. Try it online! Unbounded Version Python 2, 224 bytes def g(): q,r,t,i,j=1,0,1,0,1 while True: i+=1;j+=2;q,r,t=q*i,(2*q+r)*j,t*j;n=(q+...


21

Dyalog APL, 3 characters As a tacit phrase. ○+* Monadic ○ multiplies its argument with π, monadic * is the exponential function exp. ○+* is a train such that (○+*)ω is equal to (○ω)+(*ω). Since this is APL, the phrase works for arguments of arbitrary shape, e. g. you can pass a vector of arbitrary length. The same solution is possible in J as o....


21

Python 3, 40 39 bytes 1 byte thanks to Jonathan Allan. lambda s:sorted(s,key="145926870".find) Try it online!


20

Linux command line, 35 bytes This one is nowhere near winning, but here it is for the fun of it: ping -w2 67502862|grep -oP '.\..\d' Output (after 2 seconds): $ ping -w2 67502862|grep -oP '.\..\d' 3.14 $


Only top voted, non community-wiki answers of a minimum length are eligible