Pi计算代码高尔夫[关闭]


17

挑战

您必须以最短的长度计算pi。欢迎加入任何语言,您可以使用任何公式来计算pi。它必须能够计算pi到至少5个小数位。最短,将以字符为单位。比赛持续48小时。开始。


注意这个类似的问题指出,必须使用4 *(1 – 1/3 + 1/5 – 1/7 +…)级数来计算PI。这个问题并没有这个限制,而事实上很多答案在这里(包括最有可能胜出)将是无效的,其他的问题。因此,这不是重复的。


5
@hvd您为什么认为应该取消比赛资格?它符合规范...
belisarius博士14年

5
@hvd acos(-1)。我赢了!
水平河圣

4
这看起来很奇怪,前后矛盾。计算π必须将圆除以其直径,或者进行其他一些计算以得到π。如果我们接受355/113(除运气外与π无关),就像@ace一样,那么从逻辑上讲,我们应该接受3.14159
Nicolas Barbulesco 2014年

7
我不明白为什么人们喜欢这个问题。这是我在这里看到的最不确定和最无趣的问题之一。这个世界和hello世界之间的唯一区别是,这与Pi有关。
Cruncher

8
为了使这个问题变得有趣,它需要一个计分功能,该功能对每个字节的字节奖励pi位数。
本杰克逊

Answers:


56

Python3、7

在交互式外壳中运行

355/113

输出:3.1415929203539825,精确到小数点后6位

最后,我有一个击败APL的解决方案!

哦,如果您想知道,该比率称为密率(字面上的“精确比率”),由中国数学家祖崇智(公元429-500)提出。可以在此处找到相关的维基百科文章。祖还给出了22/7的比率作为“粗略比率”,他是第一个提出3.1415926 <= pi <= 3.1415927的数学家。


12
嗯-这实际上是一个多语言的答案。也可以在Smalltalk中使用!
blabla999

7
亵渎!这仅仅是一个计算!
mniip

3
好吧,这是一个师,并且它的精度可以满足要求……(甚至圣经也不是很准确;您不会将亵渎的标签贴上标签,对吗?3 * ;-)
blabla999 2014年

29
当我把这个问题写成一个严肃的答案但每个人
都把

20
投票最高的答案:355/113。投票率最低的答案:3+.14159。我认为差异不大。
primo 2014年

49

PHP — 132 127 125 124字节

基本的蒙特卡洛模拟。每进行10M次迭代,它将显示当前状态:

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和zamnuts的建议!

样本输出:

$ 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
找出真正计算出来的答案!
blabla999 2014年

不了解PHP,但是在JS中您可以执行类似的操作:$j+=$x*$x+$y*$y<=1;这样可以节省四个字节。
cloudfeet 2014年

1
$k+=1/4;print $j/$k可以降低到$k++;print 4*$j/$k另一个字节。
cloudfeet 2014年

@cloudfeet-进行了更改,确认的代码仍运行相同的代码。谢谢!

2
@MarkC-从概念上讲,它是在0,0到1,1的矩形中随机投掷飞镖。距0,0小于或等于距离1的那些被视为内部,否则为外部。该距离1的形状恰好是四分之一圆或π/ 4。随着样本数量的增加,[四分之一圈内的飞镖数量] / [飞镖总数]将接近π/ 4。

31

J 6

{:*._1

说明:*.给出复数的长度和角度。-1的角度是pi。{:占据列表的末尾[长度,角度]

莱比尼兹(Leibniz)系列仅适用于21个字节的缓慢收敛的系列装饰论者:

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

12
换句话说,这是atan(0) + pi。我认为三角函数和pi本身的使用不应算作“计算”。
杰森·C

@JasonC Arg(即复数的参数)不是三角函数,尽管其值类似于反正切值
mniip 2014年

1
@mniip 是的。在实部和虚部上,它只是atan(好吧,atan2)的同义词。如您所见,根据定义,它精确等于atan(0) + pi
詹森·C

25

Perl,42个字节

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

它使用Leibniz公式计算π :

Leipniz formula

999999用作最大的n,以获取五个十进制数字的精度。

结果: 3.14159165358977


这很酷!它激发了我想写一个用Java 8
大卫·康拉德

19

Piet,许多密码

不是我的答案,但这是我所见过的最佳解决方案:

Pi approximation in Piet

我的理解是,它会将圆上的像素相加,然后除以半径,然后再除一次。那是:

A = πr²  # solve for π
π = A/r²
π = (A/r)/r

在我看来,更好的方法是程序以任意大小生成此图像,然后通过Piet解释器运行它。

资料来源:http : //www.dangermouse.net/esoteric/piet/samples.html


您能解释一下它的实际作用吗?(我知道Piet背后的一般想法,但是对这个特定程序如何工作的解释将是对您的回答的很好补充)。
plannapus 2014年

我不是很了解Piet,但是我认为这实际上是测量红色圆圈的面积,然后除以半径两次,求出π= A /(r * r)
并非查尔斯

区域很清楚,因为当指针进入红色圆圈时,它将对红色区域中的编码进行计数,并在退出时将其推入堆栈(因为出口点为深红色,因此色相不变,但变暗了一步) ),这是我很难理解的“除以半径的平方”部分。
plannapus 2014年

1
@plannapus半径是深红色线中的“硬编码”,从左上角一直延伸到左边缘的下半部(在图像中很难看到)。Piet很难遵循,但是要点是彩色块的值等于它们的面积(左侧边缘的线具有r像素,圆形具有面积像素),而介于两者之间的东西只是一堆堆栈和算术运算。程序从左上方开始。右上角的文字实质上是注释。
杰森·C

2
@JasonC啊,当然!圆触及上下两边,因此深红色线必须从上侧下降到确切的中间半径!聪明!
plannapus

18

从技术上讲,我正在计算,9

0+3.14159

从技术上讲,我仍然会计算,10

PI-acos(1)

我计算很困难,8

acos(-1)

我意外的是PI,12岁

"3.14"+"159"

从技术上讲,这个答案很臭。


31
标题,大标题,我的眼睛很疼,哇。
皮埃尔·阿劳德

1
万岁,请多多指教,谢谢
Jonathan Van Matre 2014年

嘿,宝贝,想扩展我的Taylor系列吗?
杰森·C


@SimonT您没有回答我有关泰勒系列的问题。但是,当您在考虑时,请在此处查看我对问题的评论以及其他大多数答案。:P
Jason C

14

杀伤人员地雷-6

2ׯ1○1

输出3.141592654。它计算的反正弦是1的两倍。

13个字符的解决方案是:

--/4÷1-2×⍳1e6

3.141591654为我输出,符合要求的精度。
它使用简单的+ 4/1 - 4/3 + 4/5 - 4/7 ...序列进行计算。


1
哇,那是一个缓慢的融合!

我的第一个念头是“为什么不¯2○¯1?”(即acos -1)。但这给出了repl.it(3.1415926425236J¯1.1066193467303274e¯8)的复杂近似值。知道为什么吗?所有实现都这样做吗?
James Wood

+1为您的第二个解决方案。2 * asin(1)不过有点作弊。
杰森C

@JamesWood我不了解APL,但如果我不得不猜测,我会说它试图sqrt(1-theta^2)在某个点尝试执行A (它以很多触发身份弹出),并在某处失去了一定的精度,最后得到一个略微的负数1-theta^2
Jason C

1
奇怪的是仍然有一个很小的虚构部分acos -0.75。它不可能计算1 - 0.75 ^ 2为负数。
James Wood

14

J-5个字节

|^._1

这意味着|log(-1)|


巧妙地使用欧拉的身份。
primo 2014年

1
很酷,另一个代数身份答案。关于聪明的ln(e^(42*pi))/42pi*113/113
杰森C

也适用于TI-BASIC
Timtech

1
(完全无关,我希望我们可以在codegolf上使用LaTeX。)
Jason C

1
(回答完全不相关的问题,例如,我在这里通过Google图表获得。)关于主题,这是最排序的答案,因此应该被接受。
primo 2014年

14

Google计算器,48岁

stick of butter*(26557.4489*10^-9)/millimeters^3

取一小块黄油,进行高级计算,然后从中制成pi。我想,既然其他所有人都在做简单的数学答案,那么我会添加一个更独特的答案。


3
stick of butter是可爱和滑稽,但是这基本上是另一个pi*x/x+y-y代数的身份。
杰森C

10
有很多更好的方法可以用黄油来制作pi
并不是说,Charles

您是否尝试过用pi制作黄油?
mbomb007 '16

12

八度,31

quad(inline("sqrt(4-x^2)"),0,2)

通过数值积分计算半径为2的四分之一圆的面积。

octave:1> quad(inline("sqrt(4-x^2)"),0,2)
ans =     3.14159265358979

1
真好!我的投票充值+1。
杰森C


10

Python, 88

解决方案:

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

Python shell中的示例输出:

>>> print s
3.14159265359

设法避免任何进口。可以轻松地交换以使用任意精度的Decimal库;只需替换3.Decimal('3'),然后在前后设置精度,然后一元加结果即可转换精度。

与这里的许多答案不同,实际上是计算 π而不是依赖内置常量或数学伪造函数math.acos(-1),例如math.radians(180),。


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

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


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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.