Pi Calculation Code Golf

17

3

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.

poseidon

Posted 2014-02-24T20:42:44.967

Reputation: 367

Question was closed 2017-02-17T23:45:05.183

1Does it actually have to calculate pi? The shortest answers will cheat by just storing 3.14159 in a variable, start calculating from there, see that it is already known to 5 decimal places, and just print it. – hvd – 2014-02-24T20:44:10.103

It has to actually calculate pi and not just display a predefined variable or function containing pi. – poseidon – 2014-02-24T20:45:07.757

2Presumably anyone that just does 4*atan(1) should be disqualified, but it does actually calculate pi, and uses a function that does not itself contain pi. – hvd – 2014-02-24T20:58:34.353

5@hvd Why do you think it should be disqualified? It fits the specs ... – Dr. belisarius – 2014-02-24T21:53:00.887

@belisarius Well, if my objection is with the specs, pointing out that the specs allow it doesn't help. :) The OP's comment isn't part of the specs either, so if I find a language that allows π+0, that's a three-character answer, and the OP has already clarified that such answers are intended to be invalid. I don't really see 4*atan(1) as less of a cheat than that one. – hvd – 2014-02-24T22:12:56.707

@hvd Ok. Perhaps a better definition of "calculation" is in order hre – Dr. belisarius – 2014-02-24T22:16:16.283

5@hvd acos(-1). I win! – Level River St – 2014-02-24T23:47:15.677

@hvd - i've seen answers , like mine that can beat a variable with 3.14159 in it

– TheDoctor – 2014-02-25T02:05:37.143

I was originally more thinking of calculating an actual equation, like the "Libenz"(I think that is how it is spelt) equation or something similar. Not just a simple calculation, however, well done for thinking outside of the box, to those who did just do simple calculation. I am unsure as to whether to pick the actual equation ones or the just simple calculation answers as the best. Anyway, there's still over 29 hours to go, so carry on! – poseidon – 2014-02-25T16:33:56.470

1The question that is linked (making this a supposed duplicate) state 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. – Victor Stafusa – 2014-02-25T16:36:24.470

1Very true Victor. – poseidon – 2014-02-25T16:37:01.873

@Poseidon Re: Libenz: You would have done well to put "no trig functions" in the question. However none of the three most popular answers at the moment uses a trig function, and first and third most popular (ace, jpjacobs) are among the shortest anyway. Neither of the 6 char answers uses a trig function (but one of them uses a conversion of 180 degrees.) – Level River St – 2014-02-25T18:47:36.817

4This 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 – 2014-02-25T20:07:05.400

But @poseidon wants the solution to calculate. Let’s calculate… :-) – Nicolas Barbulesco – 2014-02-25T20:09:11.723

7I 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 – 2014-02-25T21:54:23.277

@Cruncher It is a simple and easy question where everyone, even with poor programming skills, can answer something acceptable in less than 10 minutes, not a hard question where I need 1 hour just to understand what I am supposed to do. – Victor Stafusa – 2014-02-26T00:30:44.933

1@poseidon Can you please add a rule that explicitly prohibits the use of built-in trigonometric functions? Seriously guys, you can't honestly believe that typing your favorite language's variant of acos(-1) is somehow in the spirit of this question (and for that matter, neither is your favorite approximate reduction of 314159 / 100000). – Jason C – 2014-02-26T03:46:50.383

3

I just finished looking through all the answers here so far. I mean really guys, of course you can find a language that let's you call somebody else's implementation of the calculation in as few characters as possible, but how is that even remotely interesting? Saying "hey guys don't forget, language X has an atan() too" is roughly equivalent to posting a link to your favorite language's documentation. Who wants to see that? If you can't be bothered to find a solution like Yimin Rong's, don't bother.

– Jason C – 2014-02-26T04:12:38.600

8To make this question interesting it needs a scoring function that rewards digits of pi per byte of code. – Ben Jackson – 2014-02-26T05:16:38.230

x86 Machine Language - 2 bytes The FLDPI assembly instruction translates to 0xD9EB in machine language - thus it could count as a 2-byte solution. – Steve S. – 2014-02-26T00:51:32.157

1It should be obvious that almost none of these people are actually calculating pi (piet solution aside). They either use Pi as part of their solution (trig identities), or are calculating an approximation of pi. It's impossible to use their solutions to ever actually get closer than they provided to PI without already having it. Anyone arguing against is just trying to make this question boring and prohibitively easy because they don't know enough math to be creative. – VoronoiPotato – 2014-02-26T13:45:37.033

1@JasonC Is this a joke? This isn't a popularity contest. This is tagged code golf. Why would somebody not use the shortest code that solves the problem. That IS what code golf is. When something leads to uninteresting answers, its because of an uninteresting question (see my earlier comment). – Cruncher – 2014-02-26T13:45:57.113

3@JasonC The question explicitly says calculate it to 5 decimal places. That is literally equivalent to saying "Make your program output 3.14159". It could potentially be much more interesting if the program had to accept the accuracy as a parameter. – Cruncher – 2014-02-26T13:47:02.900

@Cruncher because it doesn't actually solve the problem. The question asks you to "Calculate Pi" to 5 digits. Identities aren't calculation, you might as well go pi = 3.14159. Typing it in isn't the same as calculating it, you're merely asserting a reality. If I asked how you got it you would just shrug. – VoronoiPotato – 2014-02-26T13:47:30.417

1@VoronoiPotato "Calculate Pi" isn't particularly well defined. Especially saying "Calculate Pi" to 5 decimal places, means calculate an approximation. Anything the computer does is some form of computation. Again, it would be much more interesting if the program had to take accuracy as a parameter. Otherwise hardcoding is always the best solution. Programs should be formed in an input => output fashion. Restrictions on how the output is to be found, leads to questions like this. – Cruncher – 2014-02-26T13:52:07.890

@Cruncher you do realize that saying that because a computer did it it's some kind of computation is ridiculously reductive. Could someone with appropriate rep edit the question so that it excludes these identity driven answers. – VoronoiPotato – 2014-02-26T13:56:39.933

@VoronoiPotato And invalidate the highest voted answer that was valid when it was posted? In any case, you're welcome to edit it and try to get it approved. In doing so you will arrive at the intrinsic problems here. You can't exclude a special case for everything. – Cruncher – 2014-02-26T13:58:08.980

@Cruncher I'd argue that it wasn't valid, because it's not a calculation it's a thinly veiled assertion. I think there's a difference from trying to exclude a special case for everything and responding to literally the first comment on the question. – VoronoiPotato – 2014-02-26T14:03:55.850

@JasonC No I don't think its what the OP had in mind. It's just a bad question. – Cruncher – 2014-02-26T16:29:35.680

1@poseidon Does it need to display the answer, or does it just need to calculate the value and store it somewhere? – Jason C – 2014-02-26T16:46:29.147

1Come on guys, really... no more forms of 3.14159*a/a - The only difference between 355/113 and 3.14159/1 is a=113 instead of 1; what's the cut off for a? And how many levels of algebraic identities must be present for it to count? pi is not OK but ln(e^pi) is... ? (Sorry, I deleted my first previous comment by accident, then had to delete the second due to lack of context). – Jason C – 2014-02-26T17:07:44.890

3Backrolled to revision 3. A competition which last 48 hours shouldn't have it's rules changed less than 8 hours before it ends. Also, @poseidon, if you tag a competition as [tag:code-golf], common courtesy would dictate that you also select the shortest answer. – primo – 2014-02-27T01:35:07.823

1@poseidon Why did you pick ace's answer? Ignoring the fact that selecting a trig function / algebraic identity answer makes this question a categorical fail, it's not even the shortest solution posted. Double fail; or maybe that's 226*fail/113. – Jason C – 2014-02-27T02:04:33.780

3Yup. Level of unimpressed exceeds 9000 on this. – amcgregor – 2014-02-27T20:56:59.023

@Primo — Shortest does not mean nicest. In fact, it is often the opposite. – Nicolas Barbulesco – 2014-02-28T15:40:37.720

@NicolasBarbulesco Shortest is an objective winning criteria. Nicest is not. – primo – 2014-02-28T18:19:32.357

You should have made this a [tag:popularity-contest] at least... – Tobias Kienzler – 2014-03-01T10:13:02.913

Answers

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

user12205

Posted 2014-02-24T20:42:44.967

Reputation: 8 752

12mhmh - that is actually a polyglot answer. Works in Smalltalk too! – blabla999 – 2014-02-24T22:02:05.083

7Blasphemy! It's barely a calculation! – mniip – 2014-02-24T22:08:25.810

3well, 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 – 2014-02-24T22:15:41.973

2

@blabla999 http://i.imgur.com/QlJaLdt.jpg

– mniip – 2014-02-24T22:21:55.040

Holy Kruppe, this is really ingenious. And it does beat APL (unless one is using the Pi constant or Arctan.) Bravo! – Tobia – 2014-02-24T22:28:29.597

This shouldn't be a serious answer... It works on paper, chalk boards, hand calculators, cellphones, google and almost every language and object you can write (if you have brains to solve this)... – Ismael Miguel – 2014-02-25T00:17:51.350

1@Ismael — So the more compatible an answer is, the worse it should be ? – Nicolas Barbulesco – 2014-02-25T19:34:49.020

1when the answer is a joke, yes. – Ismael Miguel – 2014-02-25T19:48:49.180

29The awkward moment when I wrote this as a serious answer but everyone interprets it as a joke... – user12205 – 2014-02-25T19:50:10.803

1The ratio isn't beaten until you get to 52163/16604, and that doesn't hold for long, with 52518/16717, 52873/16830, 53228/16943, etc., being better ratios than the previous. – None – 2014-02-25T20:45:59.183

3This answer works also in the google search. Pretty nifty! – gvsrepins – 2014-02-25T21:17:19.017

@Yimin Rong Given that this ratio is proposed before 500 AD, and that this challenge is a code golf question, I think this ratio is pretty good. – user12205 – 2014-02-25T21:45:35.473

1Also works in windows calculator, and mac spotlight search lol – Cruncher – 2014-02-25T21:48:03.890

1I really don't think people's favorite approximate simplification of 314159/100000 should count here. – Jason C – 2014-02-26T03:49:57.927

20Highest voted answer: 355/113. Lowest voted answer: 3+.14159. I don't see much difference, really. – primo – 2014-02-26T09:51:57.350

3This answer no longer fits the question. As it cannot be used to generate an arbitrary number of digits of pi. – VoronoiPotato – 2014-02-26T14:33:17.470

@primo I believe the difference is that using 3+.14159 is too trivial (and is longer), and voters prefer an interesting solution to a boring one. I mean, even an idiot can figure out 3+.14159 as long as he knows how to add and subtract, but not many people are aware of the approximation ratio 355/113 – user12205 – 2014-02-26T17:14:09.283

2@ace "Not many." The population considered as a whole, perhaps. Anyone who would even care, I would propose, has known about it since high school, at the latest. – primo – 2014-02-26T17:23:21.323

1@ace Not many people may be aware that it is the closest approximation with 3-digit integers, but pretty much everybody is aware that a*b/b==a, it doesn't really become more mysterious just because a is almost pi and b is 113. In your defense, though, it is the only one with 3-digit integers that is approximate to 5 decimal places. – Jason C – 2014-02-26T20:35:36.023

@ace it doesn't matter because it does not fit the new requirements. 355/113 is arguably as trivial as typing 3+.14159 anyway, instead of addition you're doing division. The historical anecdote is neat, but this should have all been a comment not an answer. – VoronoiPotato – 2014-02-26T20:38:37.740

1@VoronoiPotato fine, if you don't like it, down vote it. Or, if you already have downvoted it, does it bug you so much when others like things you hate? I know that this currently doesn't fit the rules, when I posted it, it did. – user12205 – 2014-02-26T20:48:21.687

I can't I don't have enough rep to downvote :P. It doesn't bug me much I'm just vocalizing because I feel it missed the spirit of the competition, and this wasn't the only post that exploited poor wording in the question, it's just the highest voted. – VoronoiPotato – 2014-02-26T20:54:40.593

@poseidon Ignoring the fact that selecting a trig function / algebraic identity answer makes this challenge a categorical fail, this isn't even the shortest solution posted. Double fail for accepting it; or maybe that's 226*fail/113. – Jason C – 2014-02-27T02:05:36.127

That answer is not pi though, you'd need to do the truncate to 5-6 digits to make it correct. – Matt – 2014-03-01T16:27:13.817

This is brilliant use of code golf. The purpose is to do it in as many chars as possible, the question should be voted down not the answer.

The question could have stated to find pi to at least 20 characters where this would not have worked – Dean Meehan – 2014-03-25T16:31:21.200

49

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

user15259

Posted 2014-02-24T20:42:44.967

Reputation:

What is it doing? – Mark C – 2017-02-25T21:10:57.580

2@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. – None – 2017-04-13T02:58:39.140

5Up for an answer which really computes! – blabla999 – 2014-02-24T22:21:06.840

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 – 2014-02-27T17:45:57.400

1Also $k+=1/4; and print $j/$k could be reduced to $k++; and print 4*$j/$k for another byte. – cloudfeet – 2014-02-27T17:50:30.717

@cloudfeet - Changes made, confirmed code still runs the same. Thank you! – None – 2014-02-28T15:35:52.430

nothing mind blowing, but: using echo vs print saves you 1 byte, and <2 instead of <=1 in $j+=$x*$x+$y*$y<=1; saves you another byte. lastly, using an actual line feed instead of \n saves you yet another byte (in the src). ... +1 nice work. – zamnuts – 2014-03-02T08:48:02.977

@zamnuts - it's in floating point, so <=1 is required - will try echo, not sure about direct line feed, might confuse some people – None – 2014-03-25T15:25:04.767

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

jpjacobs

Posted 2014-02-24T20:42:44.967

Reputation: 3 440

12In 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 – 2014-02-26T03:54:57.697

@JasonC Arg (that is, argument of a complex number) is not a trigonometric function, despite having values similar to that of arctangent – mniip – 2014-02-27T03:17:16.800

1

@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 – 2014-02-27T03:20:06.363

25

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

Heiko Oberdiek

Posted 2014-02-24T20:42:44.967

Reputation: 3 841

This is cool! It inspired me to write one in Java 8. – David Conrad – 2014-03-04T18:03:03.617

19

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

Not that Charles

Posted 2014-02-24T20:42:44.967

Reputation: 1 905

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 – 2014-02-26T09:25:35.517

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 – 2014-02-26T13:05:50.390

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 – 2014-02-26T13:13:49.437

@plannapus I guess the radius is hard-coded? Looks like you grok Piet 10x more than I do. – Not that Charles – 2014-02-26T15:45:48.367

I've seen this before, it's really cool. I threw together a C implementation inspired by this here.

– Jason C – 2014-02-26T17:17:42.997

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 – 2014-02-26T17:19:21.020

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 – 2014-02-27T07:39:24.027

18

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.

Jason C

Posted 2014-02-24T20:42:44.967

Reputation: 6 253

e^iπ = -1, so iπ = (log -1) / i – Mark C – 2017-02-25T21:21:02.717

31So header, much big title, very pain for my eyes, wow. – Pierre Arlaud – 2014-02-26T09:45:55.433

1pluzz wan for much lulz, thankz – Jonathan Van Matre – 2014-02-26T19:14:07.777

Hey baby, wanna expand my Taylor series? – Jason C – 2014-02-26T19:26:13.370

@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 – 2014-02-27T05:23:13.020

14

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.

mniip

Posted 2014-02-24T20:42:44.967

Reputation: 9 396

1Wow, that's one slow convergence! – None – 2014-02-24T21:56:44.773

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 – 2014-02-25T21:29:52.267

+1 for your second solution. 2 * asin(1) is a bit of a cheat, though. – Jason C – 2014-02-26T03:56:20.110

@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 – 2014-02-26T03:59:07.323

1What'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 – 2014-02-26T08:58:29.323

@JamesWood You're right, that is weird. Huh. – Jason C – 2014-02-27T01:38:16.140

Is it likely to be an implementation-dependent thing? As I said, I tested on repl.it, which uses NGN APL, which seems quite unofficial.

– James Wood – 2014-02-27T13:41:23.267

14

J - 5 bytes

|^._1

This means |log(-1)|.

swish

Posted 2014-02-24T20:42:44.967

Reputation: 7 484

@Primo Well I did the same thing in a comment up there (iπ = ln -1 div i), but strictly speaking, e^iθ is a trigonometric function. – Mark C – 2017-02-25T21:24:55.850

@MarkC MathWorld disagrees. Any other source you can find will also. That e^iθ = cos(θ) + i·sin(θ) does not demonstrate that the complex exponential function is a trigonometric function. You could just as well claim that since ∫1/(1+x²) = tan⁻¹(x), that integration must be a trigonometric function.

– primo – 2017-02-26T07:07:12.130

Clever use of Euler's Identity. – primo – 2014-02-26T09:47:34.973

1Cool, another algebraic identity answer. About as clever as ln(e^(42*pi))/42 or pi*113/113. – Jason C – 2014-02-26T17:03:14.450

Also works in TI-BASIC – Timtech – 2014-02-26T22:17:31.267

@JasonC except that 1) it's not a simple algebraic expression, 2) it's not a trig function, and 3) the answer is not at all obvious; many programming languages would return an error. I chose to upvote this answer, because it made me stop and think about why it would even work. The examples you list of "similar" solutions, do not. – primo – 2014-02-27T10:02:07.667

@primo Sorry, I guess I mistakenly assumed rearranging e^iπ+1=0 (you yourself recognized Euler's identity) in terms of π was more algebra. It's yet another badly-specified-question-loophole identity answer. (And it's precisely the same form as the example I gave except substitute i for 42.) – Jason C – 2014-02-27T10:11:27.330

@JasonC lim n→∞ (1 + iπ/n)ⁿ = -1. I do not find this result to be obvious. ln(e^(42*π))/42 = π. I do find this result to be obvious. – primo – 2014-02-27T10:24:34.283

@primo The evaluation of the limit you stated is Euler's identity; it's precisely e^(i*pi)+1=0... and log(-1) is a (and the only) direct algebraic solution to that identity for pi (sorry, the character isn't in my clipboard any more, ha). log(-1) is not an attempt to evaluate that limit.

– Jason C – 2014-02-27T10:45:58.157

1(Totally unrelated, I wish we could use LaTeX on codegolf.) – Jason C – 2014-02-27T10:47:55.353

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 – 2014-02-27T10:51:40.170

Well, given the fact that the OP deemed these types of answers acceptable (by accepting the silly 355/113 answer), regardless of how strongly I disagree with these answers, I can definitely agree with you that this should have been the accepted one. If you really lower the bar, there's also fldpi with 5, and that TI CAS degrees-to-radians one with 4 (and another with 4 that I can't find... and I think there's a really bad 2 character one on the second page). – Jason C – 2014-02-27T10:56:20.487

14

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

Danny

Posted 2014-02-24T20:42:44.967

Reputation: 1 563

Have you tried making butter with a stick of pi? – mbomb007 – 2016-04-19T21:54:29.713

3The stick of butter is cute and funny but this is essentially yet another pi*x/x+y-y algebraic identity. – Jason C – 2014-02-26T17:24:52.743

10

There are so many better ways to make pi using a stick of butter

– Not that Charles – 2014-02-26T20:24:52.880

12

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

dcsohl

Posted 2014-02-24T20:42:44.967

Reputation: 641

1Nice! +1 when my votes recharge. – Jason C – 2014-02-26T20:38:41.773

11

Mathematica 6

180N@° 
-->3.14159

Dr. belisarius

Posted 2014-02-24T20:42:44.967

Reputation: 5 345

10

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.

amcgregor

Posted 2014-02-24T20:42:44.967

Reputation: 201

9

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]

Jerry Coffin

Posted 2014-02-24T20:42:44.967

Reputation: 539

1Can you explain, please ? – Nicolas Barbulesco – 2014-02-25T20:16:59.980

And, on some processors, what calculcation would fldpi do ? – Nicolas Barbulesco – 2014-02-25T20:22:54.540

@NicolasBarbulesco: if memory serves, it did something like 6*asin(0.5), apparently because it converges quite quickly. – Jerry Coffin – 2014-02-25T20:27:00.487

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 – 2014-02-26T04:07:36.313

@JasonC: I might agree if even a significant minority of those using higher level languages were using something like an expansion of a Taylor series or some such, but virtually all of them also using predefined sin, cos, atan, sqrt, etc. – Jerry Coffin – 2014-02-26T04:14:18.877

What I mean to say is, I think fldpi doesn't count in the same way the higher level acos doesn't count (i.e. 99% of the answers here don't count). When I said "port this to assembler" above, that applies to most of the questions here, just replace "assembler" with the relevant language. – Jason C – 2014-02-26T04:30:40.910

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 – 2014-02-26T04:50:35.263

3@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 – 2014-02-26T05:04:38.350

8

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
$ 

Digital Trauma

Posted 2014-02-24T20:42:44.967

Reputation: 64 644

+1 now that's more like it! – Jason C – 2014-02-27T01:51:24.723

@JasonC What is your opinion of application of Newton-Raphson to solve sin(x)=0 (see edit)? – Digital Trauma – 2014-04-13T17:56:37.733

6

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

Jens Renders

Posted 2014-02-24T20:42:44.967

Reputation: 1 476

6

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

qwr

Posted 2014-02-24T20:42:44.967

Reputation: 8 929

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 – 2014-02-26T05:28:22.327

Uh… no. After your modification this no longer gives valid output. (265723 ≭ π) You still need the period, just not the trailing zero. – amcgregor – 2014-02-27T21:05:15.893

@amcgregor use python 3? – qwr – 2014-02-27T21:13:35.287

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 – 2014-02-28T01:00:12.817

@amcgregor I just tested it, it works for me (python 3.3.4) – qwr – 2014-02-28T01:08:25.843

6

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.

Jason C

Posted 2014-02-24T20:42:44.967

Reputation: 6 253

6

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

Evpok

Posted 2014-02-24T20:42:44.967

Reputation: 558

1Can 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 – 2019-06-21T13:41:26.083

5

TI CAS, 35

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

TheDoctor

Posted 2014-02-24T20:42:44.967

Reputation: 7 793

1I looked back at this and i completely forget how it works :P – TheDoctor – 2014-11-09T00:06:25.400

5

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.

Victor Stafusa

Posted 2014-02-24T20:42:44.967

Reputation: 8 612

5

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.

David Herrmann

Posted 2014-02-24T20:42:44.967

Reputation: 1 544

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 – 2014-02-25T21:18:23.397

1You'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 – 2014-02-25T21:30:43.593

Yes, it's possible - just one character more... – David Herrmann – 2014-02-25T21:35:44.083

Your first answer is not as precise as your second. – Josh – 2014-03-01T18:50:10.103

Could you elaborate, please? Same algorithm, same output for me? – David Herrmann – 2014-03-01T19:49:25.103

5

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) &approx; 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

primo

Posted 2014-02-24T20:42:44.967

Reputation: 30 891

5

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

Timtech

Posted 2014-02-24T20:42:44.967

Reputation: 12 038

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 – 2015-01-14T15:37:54.900

@mbomb007 Unfortunately not, GML requires all 3 parameters. – Timtech – 2015-01-15T02:07:28.890

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 – 2014-03-01T11:04:56.157

even shorter with 1e8 instead of 999999 – izabera – 2014-03-01T11:12:02.027

5

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.

BryanJ

Posted 2014-02-24T20:42:44.967

Reputation: 151

I'm 5 years late, but this is a standard loophole that was created 4 days before this answer.

– Benjamin Urquhart – 2019-06-22T17:53:38.293

5

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

Evpok

Posted 2014-02-24T20:42:44.967

Reputation: 558

4

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

TroyAndAbed

Posted 2014-02-24T20:42:44.967

Reputation: 159

This doesn't do any calculation. – None – 2014-02-24T22:09:27.437

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 – 2014-02-24T22:11:48.637

2@user2509848 It most certainly does: it multiplies 180 by pi/180. – AJMansfield – 2014-02-24T23:15:13.733

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. – None – 2014-02-24T23:17:37.603

1

Can be shorter: http://codegolf.stackexchange.com/a/22057/14610

– Navin – 2014-02-25T14:25:10.797

Yes, thanks Navin! – TroyAndAbed – 2014-02-25T15:20:44.360

You can't convert degrees to radians without already knowing pi; this computes "output = 180 * pi / 180", which just multiplies pi by 1 and prints it. whistle Red flag on the play! – Jason C – 2014-02-26T03:37:47.377

4

R: 33 characters

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

Hopefully this follows the rules.

Mark Miller

Posted 2014-02-24T20:42:44.967

Reputation: 151

3

Ruby, 12

p 1.570796*2

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

Doorknob

Posted 2014-02-24T20:42:44.967

Reputation: 68 138

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 – 2014-02-25T02:38:56.590

@Wchar Ok, edited – Doorknob – 2014-02-25T02:42:01.517

3I 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 – 2014-02-26T03:40:05.683

3

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

Doorknob

Posted 2014-02-24T20:42:44.967

Reputation: 68 138

3

JavaScript - 19 bytes

Math.pow(29809,1/9)

Calculates the 9th root of 29809.

3.1415914903890925

primo

Posted 2014-02-24T20:42:44.967

Reputation: 30 891

3

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.

Andrew Charneski

Posted 2014-02-24T20:42:44.967

Reputation: 131

1Save some characters with alert(x), and also remove the var statements – scrblnrd3 – 2014-03-02T10:59:28.733

3

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

dfernig

Posted 2014-02-24T20:42:44.967

Reputation: 191

3

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

Knu this no toff to pic

Posted 2014-02-24T20:42:44.967

Reputation: 31

2

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
$ 

Digital Trauma

Posted 2014-02-24T20:42:44.967

Reputation: 64 644

1I 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 – 2014-02-26T04:03:03.497

1

@JasonC - point taken. So here's another answer which I think should satisfy your thirst for real calculation ;-)

– Digital Trauma – 2014-02-26T18:23:00.277

I count 6 chars, not 7! – F. Hauri – 2014-02-27T07:58:51.507

@JasonC Try this: time bc -l <<<"scale=10000;pi=4*a(1);1". This output only 1, (not pi with 9999 decimals) but load your CPU to compute. So I think that it's not only 4*pi/4 but really 4*atan(1)! – F. Hauri – 2014-02-27T08:01:51.410

1

@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 – 2014-02-27T08:22:44.553

@F.Hauri Oh, no doubt it's actually performing an atan. It's just that atan(1) is equal to pi/4. Even though bc doesn't make any kind of special optimizations for that case (why should it?), 4*atan(1) is still equal to 4*pi/4. My real point was that general trig functions that require pi to be known in order to be calculated seem like a cheat (these are all solutions that can only calculate pi because at some point, pi is known; even if it is buried in an atan implementation). – Jason C – 2014-02-27T08:23:23.503

@F.Hauri Re: precomputed strings; hey, that is interesting, I didn't know bc did that, and thanks for the link! – Jason C – 2014-02-27T08:28:23.680

@F.Hauri - thanks - I don't know how I counted 7! – Digital Trauma – 2014-02-27T15:18:24.567

1@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 – 2014-02-27T21:12:16.150

@DigitalTrauma In my opinion, no. But if you could implement a full arctan function that didn't require pi or other trig library calls in as few characters as possible, now that would be interesting and acceptable. – Jason C – 2014-02-27T22:50:17.837

2

TI CAS , 4

Assuming you're in radians mode,

180°

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

Radians:180°

(suggested by AJMansfield)

(similar to the Mathematica answer)

TheDoctor

Posted 2014-02-24T20:42:44.967

Reputation: 7 793

2Assuming 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 – 2014-02-24T22:26:02.933

2Agreed with @belisarius I'd consider Radian->Mode or similar at least 10 chars. – Timtech – 2014-02-24T22:28:11.213

2Radian mode is the default – TheDoctor – 2014-02-24T22:44:45.907

1Ok! 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 – 2014-02-24T23:15:48.407

1At 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 – 2014-02-25T01:32:00.967

I think that's also allowable on the 89 – TheDoctor – 2014-02-25T02:01:44.030

1You have to know pi to convert degrees to radians; I don't think displaying "pi*180/180" really counts... – Jason C – 2014-02-26T03:41:29.423

2

AppleScript, 8 characters

Solution :

3+.14159

Result :

3.14159

Nicolas Barbulesco

Posted 2014-02-24T20:42:44.967

Reputation: 249

1When 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 – 2014-02-25T21:53:09.957

2

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)

Oberon

Posted 2014-02-24T20:42:44.967

Reputation: 2 881

2

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:

3.141592653616969

Output:

3.141592653616969

David Conrad

Posted 2014-02-24T20:42:44.967

Reputation: 1 037

1

AppleScript, 4 characters !

Solution :

pi+0

Displayed result :

3.14159265359

Nicolas Barbulesco

Posted 2014-02-24T20:42:44.967

Reputation: 249

1

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=

Mark Jeronimus

Posted 2014-02-24T20:42:44.967

Reputation: 6 451

1

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.

Jens Renders

Posted 2014-02-24T20:42:44.967

Reputation: 1 476

1

Groovy: 25

print Math.log(10691/462)

Output is 3.141592653932079

de Jerphanion approximation

md_rasler

Posted 2014-02-24T20:42:44.967

Reputation: 201

1

APL : 2 chars

    ○1
3.141592653589793

Reference for monadic circle: http://www.microapl.co.uk/apl_help/ch_020_020_230.htm

Mark Plotnick

Posted 2014-02-24T20:42:44.967

Reputation: 1 231

1

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

WallyWest

Posted 2014-02-24T20:42:44.967

Reputation: 6 949

2alert(Math.pow(2143/22,.25) gives me a syntax error. did you forgot the last ) ? – Wolle Vanillebär Lutz – 2014-02-28T15:29:57.957

@WolleVanillebarLutz Oops! Fixed! – WallyWest – 2014-02-28T22:38:58.333

1

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

CCP

Posted 2014-02-24T20:42:44.967

Reputation: 632

1

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)

elixenide

Posted 2014-02-24T20:42:44.967

Reputation: 250

0

Python 3, 91 (with display), 82 (just calculation)

This knows that Pi is 3, then it uses the Nilakantha method to calculate Pi accurately to 6 decimal places.

p,n,s=3,2,1
while s<99:
 n,s,z=n+2,s+1,4/(n*(n+1)*(n+2))
 if s%2<1:p+=z
 else:p-=z
print(p)

It starts with the humorous 3,2,1, but also with the rather distasteful p,n,s...

Output

3.141592 395970107
The space is to separate the correct output from the incorrect.

ender_scythe

Posted 2014-02-24T20:42:44.967

Reputation: 249

0

Smalltalk, 9

1arcSin*2

will do

blabla999

Posted 2014-02-24T20:42:44.967

Reputation: 1 869

2How is using somebody else's implementation of trig identities that rely on pi to begin with in the spirit of this question? – Jason C – 2014-02-26T04:09:32.463

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 – 2014-02-26T18:56:59.830

0

Python : 8 bytes

acos(-1)

do i have to include imports??

Maltysen

Posted 2014-02-24T20:42:44.967

Reputation: 59

1This 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 – 2014-02-25T06:22:10.743

1Yes, you have to include imports. – user12205 – 2014-02-25T18:55:51.883

0

q [7 chars]

acos -1

Example

acos -1
3.141593

355%113       // [7 Chars]
3.141593

2*asin 1      // [8 Chars]
3.141593

nyi

Posted 2014-02-24T20:42:44.967

Reputation: 448

0

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

Not that Charles

Posted 2014-02-24T20:42:44.967

Reputation: 1 905

0

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

md_rasler

Posted 2014-02-24T20:42:44.967

Reputation: 201

0

Python, 27

import math
math.atan(1)*4

I left StackExchange

Posted 2014-02-24T20:42:44.967

Reputation: 159

1I'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 – 2014-02-27T20:56:26.943

0

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

izabera

Posted 2014-02-24T20:42:44.967

Reputation: 879

0

C

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

Mhmd

Posted 2014-02-24T20:42:44.967

Reputation: 2 019

"It must be able to calculate pi to at least 5 decimal places." – mbomb007 – 2015-01-14T15:40:03.700

0

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.

mirabilos

Posted 2014-02-24T20:42:44.967

Reputation: 422

0

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.

zamnuts

Posted 2014-02-24T20:42:44.967

Reputation: 263

0

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.

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

David Conrad

Posted 2014-02-24T20:42:44.967

Reputation: 1 037

I chose not to use @Navin's static block trick as I'm not sure whether it's valid. – David Conrad – 2014-03-04T18:16:32.273

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 – 2014-03-04T18:23:06.447

0

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)

Simon Kuang

Posted 2014-02-24T20:42:44.967

Reputation: 168

Can somebody help me golf this further with some bitshifts? – Simon Kuang – 2014-08-07T04:53:01.623

0

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.

Vlo

Posted 2014-02-24T20:42:44.967

Reputation: 806

0

C++ 26

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

bacchusbeale

Posted 2014-02-24T20:42:44.967

Reputation: 1 235

0

Python 3.x - 123

Sadly this has very little precision... giving only 1-2 decimal places correct.

Anyway this is a fun method of calculating pi.

import random
R = lambda: random.uniform(-1,1)
print(sum(1 for _ in range(10**6) if abs(R() + R()*1j) < 1)*4/10**6)

Caridorc

Posted 2014-02-24T20:42:44.967

Reputation: 2 254

"It must be able to calculate pi to at least 5 decimal places." – mbomb007 – 2015-01-14T15:06:46.990

0

Ruby 8

-0.0.arg 

Output takes 2 more chars:

p -0.0.arg  # => 3.141592653589793

steenslag

Posted 2014-02-24T20:42:44.967

Reputation: 2 070

-1

Java, 55

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

Hooray for static blocks ^_^

Navin

Posted 2014-02-24T20:42:44.967

Reputation: 115

2

-1. This is a direct copy of http://codegolf.stackexchange.com/a/22025/9498 . You thought of using the static block, but since this is identical to the other answer, you should have posted this idea in a comment.

– Justin – 2014-02-25T01:06:09.677

Also, that will never compile without a main method. – Isiah Meadows – 2014-02-25T04:20:14.440

@Quincunx That is why I linked it. – Navin – 2014-02-25T14:21:14.283

@impinball IIRC, main() is only needed at runtime in Java (unlike most other languages which need an entry point to compile). The static block will run before it crashes. – Navin – 2014-02-25T14:23:03.240

It doesn't, though. When Java sees it doesn't have a main() method, it doesn't even load the class and the static block never runs. At least, that's the result I get with the latest Java 8 build. – David Conrad – 2014-03-04T18:27:45.283

Hmm. It works with 1.6.0_45 but not 1.7.0_40 or 1.8.0-b129. – David Conrad – 2014-03-04T18:29:35.950

@DavidConrad Odd.... I've been using this forever 0_0 I just call System.exit(0); after the static block so it does not crash – Navin – 2014-03-05T07:31:34.890

-1

bc, 8 characters

Solution :

3+.14159

Usage :

$ bc <<< "3+.14159"
3.14159
$ 

Nicolas Barbulesco

Posted 2014-02-24T20:42:44.967

Reputation: 249

4+1 amazing technique! HOW DOES THIS EVEN WORK?? – Jason C – 2014-02-26T04:25:55.827

-1

Python, 27 chars

print "%.5f"%(355.0/113.0)

chack008

Posted 2014-02-24T20:42:44.967

Reputation: 23

-1

Windows Calculator, 1 click

Inspired by This Answer

enter image description here

Mukul Kumar

Posted 2014-02-24T20:42:44.967

Reputation: 2 585

1This answer is a blatant advertisement for your other answer. There is no relation whatsoever. – Justin – 2014-06-29T01:55:11.323

-2

Matlab or Octave

0+pi

So short stackexchange won't let me post it without this. The output:

octave:5> 0+pi
ans =  3.14159265358979

Richard

Posted 2014-02-24T20:42:44.967

Reputation: 11