Pi Hesaplama Kodu Golf [kapalı]


17

Meydan okuma

Pi'yi mümkün olan en kısa uzunlukta hesaplamanız gerekir. Herhangi bir dil katılmak için bekliyoruz ve pi hesaplamak için herhangi bir formül kullanabilirsiniz. Pi'yi en az 5 ondalık basamağa kadar hesaplayabilmelidir. En kısa, karakter cinsinden ölçülür. Yarışma 48 saat sürer. Başla.


Not : Bu benzer soru PI'nin 4 * (1 - 1/3 + 1/5 - 1/7 +…) serisi kullanılarak hesaplanması gerektiğini belirtir. Bu soru bu kısıtlamaya sahip değildir ve aslında buradaki birçok cevap (kazanma olasılığı en yüksek olanlar dahil) diğer soruda geçersiz olacaktır. Yani, bu bir kopya değil.


5
@hvd Sizce neden diskalifiye edilmeli? Teknik özelliklere uyar ...
Dr. belisarius

5
@hvd acos (-1). Ben kazandım!
Level River St

4
Bu tuhaf, tutarsız görünüyor. Π hesaplamak , bir daireyi çapına veya giving veren başka bir işleme bölmek olmalıdır. Yaptığımız kabul edersek 355/113 - şans dışında tt ile ilgisi olan -, @ace gibi, o mantıklı yaptığımız kabul etmelidir 3.14159 .
Nicolas Barbulesco

7
İnsanların neden bu soruyu sevdiğini anlamıyorum. Bu, burada gördüğüm en kötü tanımlanmış ve ilgisiz sorulardan biri. Bu ve merhaba dünya arasındaki tek fark, bunun Pi ile bir ilgisi olmasıdır.
Cruncher

8
Bu soruyu ilginç kılmak için, bayt kod başına pi basamaklarını ödüllendiren bir puanlama işlevi gerekir.
Ben Jackson

Yanıtlar:


56

Python3, 7

Etkileşimli kabukta çalışır

355/113

Çıktı:, 3.14159292035398256 ondalık basamağa doğru

Ve sonunda APL'yi yenen bir çözümüm var!

Merak ediyorsanız, bu orana 密 率 (kelimenin tam anlamıyla "kesin oran") denir ve Çinli matematikçi Zu Chongzhi (MS 429-500) tarafından önerilir. İlgili bir wikipedia makalesi burada bulunabilir . Zu da 22/7 oranını "kaba oran" olarak verdi ve 3.1415926 <= pi <= 3.1415927 öneren ilk matematikçi olduğu biliniyor.


12
mhmh - bu aslında çok dilli bir cevap. Smalltalk'ta da çalışıyor!
14:02

7
Küfür! Bu neredeyse bir hesaplama!
mniip

3
iyi, bu bir bölünme ve hassasiyeti gereksinimi karşılar ... (ve İncil bile daha az doğrudur; küfürleri etiketlemezdiniz - olur mu? 3 * ;-)
blabla999

29
Bunu ciddi bir cevap olarak yazdığım garip an ama herkes bunu bir şaka olarak yorumlar ...
user12205

20
En yüksek cevap olarak: 355/113. En düşük cevabı olarak: 3+.14159. Gerçekten fazla bir fark görmüyorum.
primo

49

PHP - 132 127 125 124 bayt

Temel Monte-Carlo simülasyonu. Her 10M yinelemede mevcut durumu yazdırır:

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

Cloudfeet ve önerileri için zamnuts sayesinde!

Örnek çıktı:

$ 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

5
Gerçekten hesaplayan bir cevap için!
14:22

PHP hakkında bilmiyorum, ama JS'de şöyle bir şey yapabilirsiniz: $j+=$x*$x+$y*$y<=1;bu size dört bayt kazandırır.
cloudfeet

1
Ayrıca $k+=1/4;ve başka bir bayt print $j/$kiçin $k++;ve print 4*$j/$kbaşka bir bayt için azaltılabilir .
cloudfeet

@cloudfeet - Değişiklikler yapıldı, onaylanan kod hala aynı şekilde çalışıyor. Teşekkür ederim!

2
@MarkC - Kavramsal olarak 0,0 ile 1,1 arasında bir dikdörtgen içinde dart atıyor. 0,0'dan 1 mesafesine eşit veya daha küçük olanlar içeride, dışarıda düşünülür. Bu mesafe 1'in şekli çeyrek daire veya π / 4 olur. [Çeyrek daire içindeki dart sayısı] / [toplam dart sayısı] örnek sayısı arttıkça yaklaşık π / 4 olacaktır.

31

J 6

{:*._1

Açıklama: *.karmaşık bir sayının uzunluğunu ve açısını verir. -1 açısı pi'dir. {:listenin kuyruğunu alır [uzunluk, açı]

Sadece yavaş yavaş yakınsama serisi-fettishistler için, 21 bayt için bir Leibniz serisi:

      +/(4*_1&^%>:@+:)i.1e6
 3.14159

12
Başka bir deyişle, bu atan(0) + pi. Trigonometrik fonksiyonların ve pi'nin kendisinin bir "hesaplama" olarak sayılması gerektiğini düşünmüyorum.
Jason C

@JasonC Arg(yani, karmaşık bir sayının argümanı), arktanjantınkine benzer değerlere sahip olmasına rağmen, trigonometrik bir fonksiyon değildir
mniip

1
@mniip Evet, öyle. Bu sadece gerçek ve hayali bölümlerde atanan (iyi, atan2) ile eşanlamlıdır. Gördüğünüz gibi, tanım gereği kesinlikle eşittir atan(0) + pi.
Jason C

25

Perl, 42 bayt

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

Leibniz formülünü kullanarak π hesaplar :

Leipniz formula

999999, beş ondalık basamak hassasiyetini elde etmek için en büyük n olarak kullanılır .

Sonuç: 3.14159165358977


Bu havalı! Java 8'de bir tane yazmam için bana ilham verdi
David Conrad

19

Piet, birçok kodek

Cevabım değil, ama bu sorun için gördüğüm en iyi çözüm:

Pi approximation in Piet

Anladığım kadarıyla, daire içindeki pikselleri toplayıp yarıçapa ve sonra tekrar böldüğü. Yani:

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


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

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

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

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

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

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.


31
So header, much big title, very pain for my eyes, wow.
Pierre Arlaud

1
pluzz wan for much lulz, thankz
Jonathan Van Matre

Hey baby, wanna expand my Taylor series?
Jason C


@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

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.


1
Wow, that's one slow convergence!

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

+1 for your second solution. 2 * asin(1) is a bit of a cheat, though.
Jason C

@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

1
What's strange is that there's still a tiny imaginary part for acos -0.75. There's no way it could calculate 1 - 0.75 ^ 2 to be negative.
James Wood

14

J - 5 bytes

|^._1

This means |log(-1)|.


Clever use of Euler's Identity.
primo

1
Cool, another algebraic identity answer. About as clever as ln(e^(42*pi))/42 or pi*113/113.
Jason C

Also works in TI-BASIC
Timtech

1
(Totally unrelated, I wish we could use LaTeX on codegolf.)
Jason C

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

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


3
The stick of butter is cute and funny but this is essentially yet another pi*x/x+y-y algebraic identity.
Jason C

10
There are so many better ways to make pi using a stick of butter
Not that Charles

Have you tried making butter with a stick of pi?
mbomb007

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

1
Nice! +1 when my votes recharge.
Jason C


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.


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]


1
Can you explain, please ?
Nicolas Barbulesco

And, on some processors, what calculcation would fldpi do ?
Nicolas Barbulesco

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

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

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

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
$ 

+1 now that's more like it!
Jason C

@JasonC What is your opinion of application of Newton-Raphson to solve sin(x)=0 (see edit)?
Digital Trauma

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

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

Uh… no. After your modification this no longer gives valid output. (265723 ≭ π) You still need the period, just not the trailing zero.
amcgregor

@amcgregor use python 3?
qwr

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

@amcgregor I just tested it, it works for me (python 3.3.4)
qwr

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.


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

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


1
Can potentially avoid the math import and sqrt call by pivoting to exponentiation instead: (6*sum(n**-2 for n in range(1,9**9)))**0.5
amcgregor

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.


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.


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

1
You're absolutely right. It is often very convenient to use (especially Ruby's) Array and Enumerable functions, though it might really not be the best idea in terms of performance and speed... Well, thinking about that, it should be possible to do the calculation with the Range.each method instead of creating a map.
David Herrmann

Yes, it's possible - just one character more...
David Herrmann

Your first answer is not as precise as your second.
Josh

Could you elaborate, please? Same algorithm, same output for me?
David Herrmann

5

TI CAS, 35

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

1
I looked back at this and i completely forget how it works :P
TheDoctor

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

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.


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

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

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

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

even shorter with 1e8 instead of 999999
izabera

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

@mbomb007 Unfortunately not, GML requires all 3 parameters.
Timtech

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

This doesn't do any calculation.

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

2
@user2509848 It most certainly does: it multiplies 180 by pi/180.
AJMansfield

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.


4

R: 33 characters

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

Hopefully this follows the rules.


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


3

Ruby, 12

p 1.570796*2

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


No, you are not technically calculating pi. You are technically calculating 3.141592, which happens to be close to pi, but will never converge to exactly acos(-1).
wchargin

@Wchar Ok, edited
Doorknob

3
I don't think hard-coding pi/2 then multiplying it by 2 really counts; the point is to calculate pi, not obfuscate a numeric literal.
Jason C

3

JavaScript - 19 bytes

Math.pow(29809,1/9)

Calculates the 9th root of 29809.

3.1415914903890925
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.