Pi: Difference between revisions

Content added Content deleted
(→‎Crystal: Updated syntaxhighlight lang=, etc...)
m (syntax highlighting fixup automation)
Line 18: Line 18:
{{trans|D}}
{{trans|D}}


<syntaxhighlight lang=11l>V ndigits = 0
<syntaxhighlight lang="11l">V ndigits = 0
V q = BigInt(1)
V q = BigInt(1)
V r = BigInt(0)
V r = BigInt(0)
Line 72: Line 72:
{{trans|FORTRAN}}
{{trans|FORTRAN}}
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<lang 360asm>* Spigot algorithm do the digits of PI 02/07/2016
<syntaxhighlight lang="360asm">* Spigot algorithm do the digits of PI 02/07/2016
PISPIG CSECT
PISPIG CSECT
USING PISPIG,R13 base register
USING PISPIG,R13 base register
Line 175: Line 175:
NBUF EQU 201 number of 5 decimals
NBUF EQU 201 number of 5 decimals
NVECT EQU 3350 nvect=ceil(nbuf*50/3)
NVECT EQU 3350 nvect=ceil(nbuf*50/3)
END PISPIG</lang>
END PISPIG</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 206: Line 206:
uses same algorithm as Go solution, from http://web.comlab.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf
uses same algorithm as Go solution, from http://web.comlab.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf
;pi_digits.adb:
;pi_digits.adb:
<lang Ada>with Ada.Command_Line;
<syntaxhighlight lang="ada">with Ada.Command_Line;
with Ada.Text_IO;
with Ada.Text_IO;
with GNU_Multiple_Precision.Big_Integers;
with GNU_Multiple_Precision.Big_Integers;
Line 317: Line 317:
end if;
end if;
Print_Pi (N);
Print_Pi (N);
end Pi_Digits;</lang>
end Pi_Digits;</syntaxhighlight>
output:
output:
<pre> 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0 2 8 8 4 1 9 7 1 6 9 3 9 9 3 7 5 1 0 5 8 2 0 9 7 4 9 4 4 5 9 2 3 0 7 8 1 6 4 0 6 2 8 6 2 0 8 9 9 8 6 2 8 0 3 4 8 2 5 3 4 2 1 1 7 0 6 7</pre>
<pre> 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0 2 8 8 4 1 9 7 1 6 9 3 9 9 3 7 5 1 0 5 8 2 0 9 7 4 9 4 4 5 9 2 3 0 7 8 1 6 4 0 6 2 8 6 2 0 8 9 9 8 6 2 8 0 3 4 8 2 5 3 4 2 1 1 7 0 6 7</pre>
Line 327: Line 327:
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
This codes uses 33 decimals places as a test case. Performance is O(2) based on the number of decimal places required.
This codes uses 33 decimals places as a test case. Performance is O(2) based on the number of decimal places required.
<lang algol68>#!/usr/local/bin/a68g --script #
<syntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #


INT base := 10;
INT base := 10;
Line 377: Line 377:
# OD #);
# OD #);
print(new line)
print(new line)
)</lang>
)</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 385: Line 385:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>q: 1
<syntaxhighlight lang="rebol">q: 1
r: 0
r: 0
t: 1
t: 1
Line 421: Line 421:
r: nr
r: nr
]
]
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 455: Line 455:
{{libheader|MPL}}
{{libheader|MPL}}
Could be optimized with Ipp functions, but runs fast enough for me as-is. Does not work in AHKLx64.
Could be optimized with Ipp functions, but runs fast enough for me as-is. Does not work in AHKLx64.
<lang autohotkey>#NoEnv
<syntaxhighlight lang="autohotkey">#NoEnv
#SingleInstance, Force
#SingleInstance, Force
SetBatchLines, -1
SetBatchLines, -1
Line 520: Line 520:
, MP_CPY(r, nr)
, MP_CPY(r, nr)
}
}
}</lang>
}</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==


==={{header|Applesoft}}===
==={{header|Applesoft}}===
<lang basic>10 REM ADOPTED FROM COMMODORE BASIC
<syntaxhighlight lang="basic">10 REM ADOPTED FROM COMMODORE BASIC
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
30 LN = INT(10*N/3)+16
30 LN = INT(10*N/3)+16
Line 577: Line 577:
550 RETURN
550 RETURN
</syntaxhighlight>
</lang>


==={{header|Atari 8-bit}}===
==={{header|Atari 8-bit}}===
<lang basic>10 REM ADOPTED FROM COMMODORE BASIC
<syntaxhighlight lang="basic">10 REM ADOPTED FROM COMMODORE BASIC
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
30 LN = INT(10*N/3)+16
30 LN = INT(10*N/3)+16
Line 631: Line 631:
530 ND = 0
530 ND = 0
550 RETURN
550 RETURN
</syntaxhighlight>
</lang>




==={{header|BASIC256}}===
==={{header|BASIC256}}===
{{Trans|Pascal}} below, and originally published by Stanley Rabinowitz in [http://www.mathpropress.com/stan/bibliography/spigot.pdf].
{{Trans|Pascal}} below, and originally published by Stanley Rabinowitz in [http://www.mathpropress.com/stan/bibliography/spigot.pdf].
<syntaxhighlight lang="basic256">cls
<lang BASIC256>cls


n =1000
n =1000
Line 694: Line 694:
print d;
print d;
end if
end if
return</lang>
return</syntaxhighlight>


Output:
Output:
Line 704: Line 704:
This works with Commodore Basic V2
This works with Commodore Basic V2


<lang basic>10 PRINT CHR$(147)
<syntaxhighlight lang="basic">10 PRINT CHR$(147)
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
30 LN = INT(10*N/3)+16
30 LN = INT(10*N/3)+16
Line 755: Line 755:
530 ND = 0
530 ND = 0
550 RETURN
550 RETURN
</syntaxhighlight>
</lang>


==={{header|Integer Basic}}===
==={{header|Integer Basic}}===
Line 761: Line 761:
Integer version was derived from the Pascal_spigot without any optimisation. It is more than 33% faster than the Applesoft version since it runs natively with integers.
Integer version was derived from the Pascal_spigot without any optimisation. It is more than 33% faster than the Applesoft version since it runs natively with integers.


<lang basic> 10 REM PI CALCULATION WITH SPIGOT
<syntaxhighlight lang="basic"> 10 REM PI CALCULATION WITH SPIGOT
100 N=100: REM MAX N=260 TO AVOID OVERFLOW
100 N=100: REM MAX N=260 TO AVOID OVERFLOW
110 LEN=(10*N)/3
110 LEN=(10*N)/3
Line 806: Line 806:
1080 IF I>0 THEN GOTO 1040
1080 IF I>0 THEN GOTO 1040
1090 RETURN
1090 RETURN
</syntaxhighlight>
</lang>


==={{header|Osborne 1 MBASIC}}===
==={{header|Osborne 1 MBASIC}}===
Line 812: Line 812:
Osborne 1 program is slightly different to allow it to keep the numbers all on the main screen rather than scrolling off to the right...
Osborne 1 program is slightly different to allow it to keep the numbers all on the main screen rather than scrolling off to the right...


<lang basic>10 REM ADOPTED FROM COMMODORE BASIC
<syntaxhighlight lang="basic">10 REM ADOPTED FROM COMMODORE BASIC
15 CR=0
15 CR=0
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
Line 865: Line 865:
530 ND = 0
530 ND = 0
550 RETURN
550 RETURN
</syntaxhighlight>
</lang>


==={{header|TRS-80 Model 4 BASIC}}===
==={{header|TRS-80 Model 4 BASIC}}===


<lang basic> 10 REM ADOPTED FROM COMMODORE BASIC
<syntaxhighlight lang="basic"> 10 REM ADOPTED FROM COMMODORE BASIC
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
30 LN = INT(10*N/3)+16
30 LN = INT(10*N/3)+16
Line 920: Line 920:
530 ND = 0
530 ND = 0
550 RETURN
550 RETURN
</syntaxhighlight>
</lang>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
===BASIC version===
===BASIC version===
<lang bbcbasic> WIDTH 80
<syntaxhighlight lang="bbcbasic"> WIDTH 80
M% = (HIMEM-END-1000) / 4
M% = (HIMEM-END-1000) / 4
DIM B%(M%)
DIM B%(M%)
Line 946: Line 946:
E% = D% MOD 100 : L% = 2
E% = D% MOD 100 : L% = 2
ENDCASE
ENDCASE
NEXT</lang>
NEXT</syntaxhighlight>


===Assembler version===
===Assembler version===
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
The first 250,000 digits output have been verified.
The first 250,000 digits output have been verified.
<lang bbcbasic> DIM P% 32
<syntaxhighlight lang="bbcbasic"> DIM P% 32
[OPT 2 :.pidig mov ebp,eax :.pi1 imul edx,ecx : mov eax,[ebx+ecx*4]
[OPT 2 :.pidig mov ebp,eax :.pi1 imul edx,ecx : mov eax,[ebx+ecx*4]
imul eax,100 : add eax,edx : cdq : div ebp : mov [ebx+ecx*4],edx
imul eax,100 : add eax,edx : cdq : div ebp : mov [ebx+ecx*4],edx
Line 973: Line 973:
E% = D% MOD 100 : L% = 2
E% = D% MOD 100 : L% = 2
ENDCASE
ENDCASE
NEXT</lang>
NEXT</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 996: Line 996:
{{works with|GNU bc}}
{{works with|GNU bc}}
{{works with|OpenBSD bc}}
{{works with|OpenBSD bc}}
<lang bc>#!/usr/bin/bc -l
<syntaxhighlight lang="bc">#!/usr/bin/bc -l


scaleinc= 20
scaleinc= 20
Line 1,025: Line 1,025:
scale= wantscale
scale= wantscale
oldpi= pi / 1
oldpi= pi / 1
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,054: Line 1,054:
=={{header|Bracmat}}==
=={{header|Bracmat}}==
{{trans|Icon_and_Unicon}}
{{trans|Icon_and_Unicon}}
<lang bracmat> ( pi
<syntaxhighlight lang="bracmat"> ( pi
= f,q r t k n l,first
= f,q r t k n l,first
. !arg:((=?f),?q,?r,?t,?k,?n,?l)
. !arg:((=?f),?q,?r,?t,?k,?n,?l)
Line 1,082: Line 1,082:
)
)
)
)
& pi$((=.put$!arg),1,0,1,1,3,3)</lang>
& pi$((=.put$!arg),1,0,1,1,3,3)</syntaxhighlight>
Output:
Output:
<pre>3.1415926535897932384626433832795028841971693993751058209749445923078164062
<pre>3.1415926535897932384626433832795028841971693993751058209749445923078164062
Line 1,151: Line 1,151:


Using Machin's formula. The "continuous printing" part is silly: the algorithm really calls for a preset number of digits, so the program repeatedly calculates Pi digits with increasing length and chop off leading digits already displayed. But it's still faster than the unbounded Spigot method by an order of magnitude, at least for the first 100k digits.
Using Machin's formula. The "continuous printing" part is silly: the algorithm really calls for a preset number of digits, so the program repeatedly calculates Pi digits with increasing length and chop off leading digits already displayed. But it's still faster than the unbounded Spigot method by an order of magnitude, at least for the first 100k digits.
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <gmp.h>
#include <gmp.h>
Line 1,218: Line 1,218:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Line 1,224: Line 1,224:
{{trans|Java}}
{{trans|Java}}


<syntaxhighlight lang=csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Numerics;
using System.Numerics;


Line 1,277: Line 1,277:
Adopted Version:
Adopted Version:
{{libheader|System.Numerics}}
{{libheader|System.Numerics}}
<syntaxhighlight lang=csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 1,366: Line 1,366:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_int.hpp>


Line 1,421: Line 1,421:
std::cout << *++g; // increment to the next digit and print
std::cout << *++g; // increment to the next digit and print
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,429: Line 1,429:
=={{header|Clojure}}==
=={{header|Clojure}}==
{{Trans|Python}}
{{Trans|Python}}
<lang lisp>(ns pidigits
<syntaxhighlight lang="lisp">(ns pidigits
(:gen-class))
(:gen-class))


Line 1,467: Line 1,467:
(println))
(println))
(print q))
(print q))
</syntaxhighlight>
</lang>
{{Output}}
{{Output}}
<pre>
<pre>
Line 1,478: Line 1,478:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun pi-spigot ()
<syntaxhighlight lang="lisp">(defun pi-spigot ()
(labels
(labels
((g (q r t1 k n l)
((g (q r t1 k n l)
Line 1,502: Line 1,502:
(* t1 l)))
(* t1 l)))
(+ l 2))))))
(+ l 2))))))
(g 1 0 1 1 3 3)))</lang>
(g 1 0 1 1 3 3)))</syntaxhighlight>
{{out}}
{{out}}
<pre>CL-USER> (pi-spigot)
<pre>CL-USER> (pi-spigot)
Line 1,509: Line 1,509:
=={{header|Crystal}}==
=={{header|Crystal}}==
{{trans|Ruby}}
{{trans|Ruby}}
<syntaxhighlight lang=ruby>require "big"
<syntaxhighlight lang="ruby">require "big"


def pi
def pi
Line 1,546: Line 1,546:
=={{header|D}}==
=={{header|D}}==
This modified [[wp:Spigot_algorithm|Spigot algorithm]] does not continue infinitely, because its required memory grow as the number of digits need to print.
This modified [[wp:Spigot_algorithm|Spigot algorithm]] does not continue infinitely, because its required memory grow as the number of digits need to print.
<syntaxhighlight lang=d>import std.stdio, std.conv, std.string;
<syntaxhighlight lang="d">import std.stdio, std.conv, std.string;


struct PiDigits {
struct PiDigits {
Line 1,597: Line 1,597:
534211706</pre>
534211706</pre>
===Alternative version===
===Alternative version===
<syntaxhighlight lang=d>import std.stdio, std.bigint;
<syntaxhighlight lang="d">import std.stdio, std.bigint;


void main() {
void main() {
Line 1,656: Line 1,656:


introcs dot cs dot princeton dot edu slash java slash data slash pi-10million.txt
introcs dot cs dot princeton dot edu slash java slash data slash pi-10million.txt
<lang delphi>
<syntaxhighlight lang="delphi">
unit Pi_BBC_Main;
unit Pi_BBC_Main;


Line 1,794: Line 1,794:


end.
end.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,810: Line 1,810:
With only a few changes (noted in the comments), the same code can be used to
With only a few changes (noted in the comments), the same code can be used to
output the first 2070 digits of e.
output the first 2070 digits of e.
<lang edsac>
<syntaxhighlight lang="edsac">
[EDSAC program, Initial Orders 2.
[EDSAC program, Initial Orders 2.
Calculates digits of pi by spigot algorithm.
Calculates digits of pi by spigot algorithm.
Line 2,030: Line 2,030:
E 11 Z [define entry point]
E 11 Z [define entry point]
P F [acc = 0 on entry]
P F [acc = 0 on entry]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,041: Line 2,041:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<lang elixir>defmodule Pi do
<syntaxhighlight lang="elixir">defmodule Pi do
def calc, do: calc(1,0,1,1,3,3,0)
def calc, do: calc(1,0,1,1,3,3,0)
Line 2,057: Line 2,057:
end
end


Pi.calc</lang>
Pi.calc</syntaxhighlight>


{{out}}
{{out}}
Line 2,080: Line 2,080:


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang=erlang>% Implemented by Arjun Sunel
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(pi_calculation).
-module(pi_calculation).
-export([main/0]).
-export([main/0]).
Line 2,141: Line 2,141:
===Translation of Haskell===
===Translation of Haskell===
{{trans|Haskell}}
{{trans|Haskell}}
<syntaxhighlight lang=fsharp>let rec g q r t k n l = seq {
<syntaxhighlight lang="fsharp">let rec g q r t k n l = seq {
if 4I*q+r-t < n*t
if 4I*q+r-t < n*t
then
then
Line 2,160: Line 2,160:
===As an Unfold===
===As an Unfold===
Haskell can probably do this as an unfold, it has not so I shall in F#
Haskell can probably do this as an unfold, it has not so I shall in F#
<syntaxhighlight lang=fsharp>
<syntaxhighlight lang="fsharp">
// Generate Pi as above using unfold. Nigel Galloway: March 15th., 2022
// Generate Pi as above using unfold. Nigel Galloway: March 15th., 2022
let π()=Seq.unfold(fun(q,r,t,k,n,l)->Some(if 4I*q+r-t < n*t then(Some(int n),((10I*q),(10I*(r-n*t)),t,k,((10I*(3I*q+r))/t-10I*n),l)) else (None,((q*k),((2I*q+r)*l),(t*l),(k+1I),((q*(7I*k+2I)+r*l)/(t*l)),(l+2I)))))(1I,0I,1I,1I,3I,3I)|>Seq.choose id
let π()=Seq.unfold(fun(q,r,t,k,n,l)->Some(if 4I*q+r-t < n*t then(Some(int n),((10I*q),(10I*(r-n*t)),t,k,((10I*(3I*q+r))/t-10I*n),l)) else (None,((q*k),((2I*q+r)*l),(t*l),(k+1I),((q*(7I*k+2I)+r*l)/(t*l)),(l+2I)))))(1I,0I,1I,1I,3I,3I)|>Seq.choose id
Line 2,168: Line 2,168:
=={{header|Factor}}==
=={{header|Factor}}==
{{trans|Oforth}}
{{trans|Oforth}}
<lang factor>USING: combinators.extras io kernel locals math prettyprint ;
<syntaxhighlight lang="factor">USING: combinators.extras io kernel locals math prettyprint ;
IN: rosetta-code.pi
IN: rosetta-code.pi


Line 2,188: Line 2,188:
] forever ;
] forever ;


MAIN: calc-pi-digits</lang>
MAIN: calc-pi-digits</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
This is a modernized version of the example Fortran programme written by S. Rabinowitz in 1991. It works in base 100000 and the key step is the initialisation of all elements of VECT to 2. The format code of I5.5 means I5 output but with all leading spaces made zero so that 66 comes out as "00066", not " 66".
This is a modernized version of the example Fortran programme written by S. Rabinowitz in 1991. It works in base 100000 and the key step is the initialisation of all elements of VECT to 2. The format code of I5.5 means I5 output but with all leading spaces made zero so that 66 comes out as "00066", not " 66".


<syntaxhighlight lang="fortran">
<lang Fortran>
program pi
program pi
implicit none
implicit none
Line 2,214: Line 2,214:
write (*,'(i2,"."/(1x,10i5.5))') buffer
write (*,'(i2,"."/(1x,10i5.5))') buffer
end program pi
end program pi
</syntaxhighlight>
</lang>
The output is accumulated in BUFFER then written in one go at the end, but it could be written as successive values as each is calculated without much extra nitpickery: instead of <code>BUFFER(N) = MORE + K</code> for example just <code>WRITE (*,"(I5.5)") MORE + K</code> and no need for array BUFFER.
The output is accumulated in BUFFER then written in one go at the end, but it could be written as successive values as each is calculated without much extra nitpickery: instead of <code>BUFFER(N) = MORE + K</code> for example just <code>WRITE (*,"(I5.5)") MORE + K</code> and no need for array BUFFER.
<pre>
<pre>
Line 2,242: Line 2,242:
This is an alternate version using an unbounded spigot. Higher precision is accomplished by using the Fortran Multiple Precision
This is an alternate version using an unbounded spigot. Higher precision is accomplished by using the Fortran Multiple Precision
Library, FMLIB (http://myweb.lmu.edu/dmsmith/fmlib.html), provided by Dr. David M. Smith (dsmith@lmu.edu), Mathematics Professor (Emeritus) at Loyola Marymount University. We use the default precision which is about 50 significant digits.
Library, FMLIB (http://myweb.lmu.edu/dmsmith/fmlib.html), provided by Dr. David M. Smith (dsmith@lmu.edu), Mathematics Professor (Emeritus) at Loyola Marymount University. We use the default precision which is about 50 significant digits.
<syntaxhighlight lang="fortran">
<lang Fortran>
!================================================
!================================================
program pi_spigot_unbounded
program pi_spigot_unbounded
Line 2,291: Line 2,291:


end program
end program
</syntaxhighlight>
</lang>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
{{libheader|GMP}}
{{libheader|GMP}}
<lang freebasic>' version 05-07-2018
<syntaxhighlight lang="freebasic">' version 05-07-2018
' compile with: fbc -s console
' compile with: fbc -s console


Line 2,348: Line 2,348:
mpz_set(r, tmp2)
mpz_set(r, tmp2)
End If
End If
Loop</lang>
Loop</syntaxhighlight>
{{out}}
{{out}}
<pre>3.
<pre>3.
Line 2,366: Line 2,366:
The code for <code>compute_pi()</code> is from [http://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf]. The number of digits may be given on the command line as an argument. If there's no argument, the program will run until interrupted.
The code for <code>compute_pi()</code> is from [http://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf]. The number of digits may be given on the command line as an argument. If there's no argument, the program will run until interrupted.


<lang funl>def compute_pi =
<syntaxhighlight lang="funl">def compute_pi =
def g( q, r, t, k, n, l ) =
def g( q, r, t, k, n, l ) =
if 4*q + r - t < n*t
if 4*q + r - t < n*t
Line 2,385: Line 2,385:
print( d )
print( d )


println()</lang>
println()</syntaxhighlight>


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
This old-school code still works on Mac OS Monterey and is expected to work on Ventura, but it needs a modern refactoring.
This old-school code still works on Mac OS Monterey and is expected to work on Ventura, but it needs a modern refactoring.
<lang futurebasic>
<syntaxhighlight lang="futurebasic">


_maxlong = 0x7fffffff
_maxlong = 0x7fffffff
Line 2,559: Line 2,559:


HandleEvents
HandleEvents
</syntaxhighlight>
</lang>


Output:
Output:
Line 2,641: Line 2,641:
Code below is a simplistic translation of Haskell code in [http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/spigot.pdf Unbounded Spigot Algorithms for the Digits of Pi]. This is the algorithm specified for the [http://shootout.alioth.debian.org/u64q/performance.php?test=pidigits pidigits] benchmark of the [http://shootout.alioth.debian.org/ Computer Language Benchmarks Game].
Code below is a simplistic translation of Haskell code in [http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/spigot.pdf Unbounded Spigot Algorithms for the Digits of Pi]. This is the algorithm specified for the [http://shootout.alioth.debian.org/u64q/performance.php?test=pidigits pidigits] benchmark of the [http://shootout.alioth.debian.org/ Computer Language Benchmarks Game].
(The standard Go distribution includes [http://golang.org/test/bench/shootout/pidigits.go source] submitted to the benchmark site, and that code runs stunning faster than the code below.)
(The standard Go distribution includes [http://golang.org/test/bench/shootout/pidigits.go source] submitted to the benchmark site, and that code runs stunning faster than the code below.)
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 2,723: Line 2,723:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
{{trans|Java}}
{{trans|Java}}
Solution:
Solution:
<lang groovy>BigInteger q = 1, r = 0, t = 1, k = 1, n = 3, l = 3
<syntaxhighlight lang="groovy">BigInteger q = 1, r = 0, t = 1, k = 1, n = 3, l = 3
String nn
String nn
boolean first = true
boolean first = true
Line 2,737: Line 2,737:
: ['' , first, q*k , (2*q + r)*l , t*l, k + 1, (q*(7*k + 2) + r*l)/(t*l), l + 2]
: ['' , first, q*k , (2*q + r)*l , t*l, k + 1, (q*(7*k + 2) + r*l)/(t*l), l + 2]
print nn
print nn
}</lang>
}</syntaxhighlight>


Output (thru first 1000 iterations):
Output (thru first 1000 iterations):
Line 2,744: Line 2,744:
=={{header|Haskell}}==
=={{header|Haskell}}==
The code from [http://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf]:
The code from [http://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf]:
<lang haskell>pi_ = g (1, 0, 1, 1, 3, 3)
<syntaxhighlight lang="haskell">pi_ = g (1, 0, 1, 1, 3, 3)
where
where
g (q, r, t, k, n, l) =
g (q, r, t, k, n, l) =
Line 2,762: Line 2,762:
, k + 1
, k + 1
, div (q * (7 * k + 2) + r * l) (t * l)
, div (q * (7 * k + 2) + r * l) (t * l)
, l + 2)</lang>
, l + 2)</syntaxhighlight>


===Complete command-line program===
===Complete command-line program===
Line 2,768: Line 2,768:
{{Works with|GHC|7.4.1}}
{{Works with|GHC|7.4.1}}


<lang haskell>#!/usr/bin/runhaskell
<syntaxhighlight lang="haskell">#!/usr/bin/runhaskell


import Control.Monad
import Control.Monad
Line 2,785: Line 2,785:
main = do
main = do
hSetBuffering stdout $ BlockBuffering $ Just 80
hSetBuffering stdout $ BlockBuffering $ Just 80
forM_ digs putChar</lang>
forM_ digs putChar</syntaxhighlight>


{{out}}
{{out}}
Line 2,794: Line 2,794:
===Quicker, Unverified Algorithm ===
===Quicker, Unverified Algorithm ===
Snippet verbatim from source .pdf:
Snippet verbatim from source .pdf:
<lang Haskell>piG3 = g(1,180,60,2) where
<syntaxhighlight lang="haskell">piG3 = g(1,180,60,2) where
g(q,r,t,i) = let (u,y)=(3*(3*i+1)*(3*i+2),div(q*(27*i-12)+5*r)(5*t))
g(q,r,t,i) = let (u,y)=(3*(3*i+1)*(3*i+2),div(q*(27*i-12)+5*r)(5*t))
in y : g(10*q*i*(2*i-1),10*u*(q*(5*i-2)+r-y*t),t*u,i+1)</lang>
in y : g(10*q*i*(2*i-1),10*u*(q*(5*i-2)+r-y*t),t*u,i+1)</syntaxhighlight>
This is more efficient because each term converges in less than one step, so no checking needs to be done partway through the iteration. Only caveat is that the convergence is ''on average'' slightly over one digit, so there is a chance that, if one checked enough digits, one may find a gap where a digit would be incorrect. Though it seems to be OK for the first 100k digits, or so.
This is more efficient because each term converges in less than one step, so no checking needs to be done partway through the iteration. Only caveat is that the convergence is ''on average'' slightly over one digit, so there is a chance that, if one checked enough digits, one may find a gap where a digit would be incorrect. Though it seems to be OK for the first 100k digits, or so.


Line 2,803: Line 2,803:
=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
{{Trans|PicoLisp}} based on Jeremy Gibbons' Haskell solution.
{{Trans|PicoLisp}} based on Jeremy Gibbons' Haskell solution.
<lang icon>procedure pi (q, r, t, k, n, l)
<syntaxhighlight lang="icon">procedure pi (q, r, t, k, n, l)
first := "yes"
first := "yes"
repeat { # infinite loop
repeat { # infinite loop
Line 2,830: Line 2,830:
procedure main ()
procedure main ()
every (writes (pi (1,0,1,1,3,3)))
every (writes (pi (1,0,1,1,3,3)))
end</lang>
end</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
<lang j>pi=: 3 :0
<syntaxhighlight lang="j">pi=: 3 :0
echo"0 '3.1'
echo"0 '3.1'
i=. 0
i=. 0
Line 2,839: Line 2,839:
echo -/ 1 10 * <.@o. 10x ^ 1 0 + i
echo -/ 1 10 * <.@o. 10x ^ 1 0 + i
end.
end.
)</lang>
)</syntaxhighlight>
Example use:
Example use:
<lang j> pi''
<syntaxhighlight lang="j"> pi''
3
3
.
.
Line 2,853: Line 2,853:
5
5
3
3
...</lang>
...</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{trans|Icon}}
{{trans|Icon}}
<lang java>import java.math.BigInteger ;
<syntaxhighlight lang="java">import java.math.BigInteger ;


public class Pi {
public class Pi {
Line 2,901: Line 2,901:
p.calcPiDigits() ;
p.calcPiDigits() ;
}
}
}</lang>
}</syntaxhighlight>


Output :
Output :
Line 2,914: Line 2,914:
process.stdout.write will work in Node.js; to make this work in a browser, change it to document.body.textContent += .
process.stdout.write will work in Node.js; to make this work in a browser, change it to document.body.textContent += .


<lang>let q = 1n, r = 180n, t = 60n, i = 2n;
<syntaxhighlight lang="text">let q = 1n, r = 180n, t = 60n, i = 2n;
for (;;) {
for (;;) {
let y = (q*(27n*i-12n)+5n*r)/(5n*t);
let y = (q*(27n*i-12n)+5n*r)/(5n*t);
Line 2,924: Line 2,924:
process.stdout.write(y.toString());
process.stdout.write(y.toString());
if (i === 3n) { process.stdout.write('.'); }
if (i === 3n) { process.stdout.write('.'); }
}</lang>
}</syntaxhighlight>


=== Web Page version ===
=== Web Page version ===
Line 2,930: Line 2,930:
This shows how to load the previous code into a webpage that writes digits out without freezing the browser
This shows how to load the previous code into a webpage that writes digits out without freezing the browser


<lang html><html><head><script src='https://rawgit.com/andyperlitch/jsbn/v1.1.0/index.js'></script></head>
<syntaxhighlight lang="html"><html><head><script src='https://rawgit.com/andyperlitch/jsbn/v1.1.0/index.js'></script></head>
<body style="width: 100%"><tt id="pi"></tt><tt>...</tt>
<body style="width: 100%"><tt id="pi"></tt><tt>...</tt>
<script async defer>
<script async defer>
Line 2,973: Line 2,973:
calcPi();
calcPi();
</script>
</script>
</body></html></lang>
</body></html></syntaxhighlight>


=== Web Page using BigInt ===
=== Web Page using BigInt ===
Line 2,979: Line 2,979:
Above converted to use BigInt
Above converted to use BigInt


<lang html><html>
<syntaxhighlight lang="html"><html>
<head>
<head>
</head>
</head>
Line 3,026: Line 3,026:
</script>
</script>
</body>
</body>
</html></lang>
</html></syntaxhighlight>
Note: removing the parameters to continueCalcPi() as shown may eat (even) more memory, not entirely sure about that.
Note: removing the parameters to continueCalcPi() as shown may eat (even) more memory, not entirely sure about that.


Line 3,032: Line 3,032:
Returns an approximation of Pi.
Returns an approximation of Pi.


<lang>var calcPi = function() {
<syntaxhighlight lang="text">var calcPi = function() {
var n = 20000;
var n = 20000;
var pi = 0;
var pi = 0;
Line 3,045: Line 3,045:
}
}
return pi;
return pi;
}</lang>
}</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Line 3,069: Line 3,069:
spigot grow very slightly more than linearly.
spigot grow very slightly more than linearly.


<lang jq># The Gibbons spigot, in the mold of the [[#Groovy]] and [[#Python]] programs shown on this page.
<syntaxhighlight lang="jq"># The Gibbons spigot, in the mold of the [[#Groovy]] and [[#Python]] programs shown on this page.
# The "bigint" functions needed are:
# The "bigint" functions needed are:
# long_minus long_add long_multiply long_div
# long_minus long_add long_multiply long_div
Line 3,127: Line 3,127:
;
;


pi_spigot</lang>
pi_spigot</syntaxhighlight>
{{out}}
{{out}}
<div style="overflow:scroll; height:200px;">
<div style="overflow:scroll; height:200px;">
<lang sh>$ jq -M -n -c -f pi.bigint.jq
<syntaxhighlight lang="sh">$ jq -M -n -c -f pi.bigint.jq
[0,9,"3"]
[0,9,"3"]
[1,14,"1"]
[1,14,"1"]
Line 3,435: Line 3,435:
[302,8623,"2"]
[302,8623,"2"]
...
...
</lang></div>
</syntaxhighlight></div>


=={{header|Julia}}==
=={{header|Julia}}==
Julia comes with built-in support for computing π in arbitrary precision (using the GNU MPFR library). This implementation computes π at precisions that are repeatedly doubled as more digits are needed, printing one digit at a time and never terminating (until it runs out of memory) as specified:
Julia comes with built-in support for computing π in arbitrary precision (using the GNU MPFR library). This implementation computes π at precisions that are repeatedly doubled as more digits are needed, printing one digit at a time and never terminating (until it runs out of memory) as specified:
<lang julia>let prec = precision(BigFloat), spi = "", digit = 1
<syntaxhighlight lang="julia">let prec = precision(BigFloat), spi = "", digit = 1
while true
while true
if digit > lastindex(spi)
if digit > lastindex(spi)
Line 3,449: Line 3,449:
digit += 1
digit += 1
end
end
end</lang>
end</syntaxhighlight>


Output:
Output:
Line 3,456: Line 3,456:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


import java.math.BigInteger
import java.math.BigInteger
Line 3,500: Line 3,500:
}
}


fun main(args: Array<String>) = calcPi()</lang>
fun main(args: Array<String>) = calcPi()</syntaxhighlight>


{{out}}
{{out}}
Line 3,509: Line 3,509:
=={{header|Lasso}}==
=={{header|Lasso}}==
Based off [http://crypto.stanford.edu/pbc/notes/pi/code.html Dik T. Winter's C implementation of Beeler et al. 1972, Item 120].
Based off [http://crypto.stanford.edu/pbc/notes/pi/code.html Dik T. Winter's C implementation of Beeler et al. 1972, Item 120].
<lang Lasso>#!/usr/bin/lasso9
<syntaxhighlight lang="lasso">#!/usr/bin/lasso9
define generatePi => {
define generatePi => {
Line 3,539: Line 3,539:
loop(200) => {
loop(200) => {
stdout(#pi_digits())
stdout(#pi_digits())
}</lang>
}</syntaxhighlight>
Output (first 100 places):
Output (first 100 places):
<pre>3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067
<pre>3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067
Line 3,546: Line 3,546:
=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
Pretty slow if you run for over 100 digits...
Pretty slow if you run for over 100 digits...
<lang lb> ndigits = 0
<syntaxhighlight lang="lb"> ndigits = 0


q = 1
q = 1
Line 3,580: Line 3,580:
wend
wend


end</lang>
end</syntaxhighlight>
<pre>
<pre>
3.141592653589793238462643383279502884197
3.141592653589793238462643383279502884197
Line 3,589: Line 3,589:
=={{header|Lua}}==
=={{header|Lua}}==
{{trans|Pascal}}
{{trans|Pascal}}
<lang lua>a = {}
<syntaxhighlight lang="lua">a = {}
n = 1000
n = 1000
len = math.modf( 10 * n / 3 )
len = math.modf( 10 * n / 3 )
Line 3,629: Line 3,629:
end
end
end
end
print( predigit )</lang>
print( predigit )</syntaxhighlight>
<pre>03141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086 ...</pre>
<pre>03141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086 ...</pre>


Line 3,639: Line 3,639:




<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkpi {
Module Checkpi {
Module FindPi(Digits){
Module FindPi(Digits){
Line 3,735: Line 3,735:
Modules ? ' current module exist
Modules ? ' current module exist
Stack ' Stack of values ' has to be empty, we didn't use current stack for values.
Stack ' Stack of values ' has to be empty, we didn't use current stack for values.
</syntaxhighlight>
</lang>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
User can interrupt computation using "Alt+." or "Cmd+." on a Mac.
User can interrupt computation using "Alt+." or "Cmd+." on a Mac.
<lang Mathematica>WriteString[$Output, "3."];
<syntaxhighlight lang="mathematica">WriteString[$Output, "3."];
For[i = -1, True, i--,
For[i = -1, True, i--,
WriteString[$Output, RealDigits[Pi, 10, 1, i][[1, 1]]]; Pause[.05]];</lang>
WriteString[$Output, RealDigits[Pi, 10, 1, i][[1, 1]]]; Pause[.05]];</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
Matlab and Octave use double precision numbers per default, and pi is a builtin constant value. Arbitrary precision is only implemented in some additional toolboxes (e.g. symbolic toolbox).
Matlab and Octave use double precision numbers per default, and pi is a builtin constant value. Arbitrary precision is only implemented in some additional toolboxes (e.g. symbolic toolbox).
<lang MATLAB>pi</lang>
<syntaxhighlight lang="matlab">pi</syntaxhighlight>
<pre>
<pre>
>> pi
>> pi
Line 3,761: Line 3,761:
=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
{{trans|Java}}
{{trans|Java}}
<lang Nanoquery>q = 1; r = 0; t = 1
<syntaxhighlight lang="nanoquery">q = 1; r = 0; t = 1
k = 1; n = 3; l = 3
k = 1; n = 3; l = 3


Line 3,788: Line 3,788:
r = nr
r = nr
end if
end if
end while</lang>
end while</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,796: Line 3,796:
=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{trans|Java}}
{{trans|Java}}
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
options replace format comments java crossref symbols binary
import java.math.BigInteger
import java.math.BigInteger
Line 3,858: Line 3,858:
method isFalse() private static returns boolean
method isFalse() private static returns boolean
return \isTrue()
return \isTrue()
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,866: Line 3,866:
=={{header|Nim}}==
=={{header|Nim}}==
{{libheader|bigints}}
{{libheader|bigints}}
<lang nim>import bigints
<syntaxhighlight lang="nim">import bigints


var
var
Line 3,911: Line 3,911:
echo ""
echo ""
i = 0
i = 0
eliminateDigit d</lang>
eliminateDigit d</syntaxhighlight>


{{out}}
{{out}}
Line 3,923: Line 3,923:
{{trans|D}}
{{trans|D}}
{{libheader|bignum}}
{{libheader|bignum}}
<lang Nim>import bignum
<syntaxhighlight lang="nim">import bignum


proc calcPi() =
proc calcPi() =
Line 3,954: Line 3,954:
r = nr
r = nr


calcPi()</lang>
calcPi()</syntaxhighlight>


{{out}}
{{out}}
Line 3,965: Line 3,965:
=={{header|OCaml}}==
=={{header|OCaml}}==
The Constructive Real library [http://www.lri.fr/~filliatr/creal.en.html Creal] contains an infinite-precision Pi, so we can just print out its digits.
The Constructive Real library [http://www.lri.fr/~filliatr/creal.en.html Creal] contains an infinite-precision Pi, so we can just print out its digits.
<lang OCaml>open Creal;;
<syntaxhighlight lang="ocaml">open Creal;;


let block = 100 in
let block = 100 in
Line 3,976: Line 3,976:
flush stdout;
flush stdout;
incr counter
incr counter
done</lang>
done</syntaxhighlight>
However that is cheating if you want to see an algorithm to generate Pi. Since the Spigot algorithm is already used in the [http://benchmarksgame.alioth.debian.org/u64q/program.php?test=pidigits&lang=ocaml&id=1 pidigits] program, this implements [http://mathworld.wolfram.com/Machin-LikeFormulas.html Machin's formula].
However that is cheating if you want to see an algorithm to generate Pi. Since the Spigot algorithm is already used in the [http://benchmarksgame.alioth.debian.org/u64q/program.php?test=pidigits&lang=ocaml&id=1 pidigits] program, this implements [http://mathworld.wolfram.com/Machin-LikeFormulas.html Machin's formula].
<lang OCaml>open Num
<syntaxhighlight lang="ocaml">open Num


(* series for: c*atan(1/k) *)
(* series for: c*atan(1/k) *)
Line 4,020: Line 4,020:
incr npr; shift := !shift */ base;
incr npr; shift := !shift */ base;
) else (acc := !acc */ d_acc);
) else (acc := !acc */ d_acc);
done</lang>
done</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: calcPiDigits
<syntaxhighlight lang="oforth">: calcPiDigits
| q r t k n l |
| q r t k n l |
1 ->q 0 ->r 1 ->t 1 ->k 3 ->n 3 -> l
1 ->q 0 ->r 1 ->t 1 ->k 3 ->n 3 -> l
Line 4,043: Line 4,043:
k 1+ ->k
k 1+ ->k
]
]
] ;</lang>
] ;</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
{{trans|Scheme}}
{{trans|Scheme}}


<lang scheme>
<syntaxhighlight lang="scheme">
; 'numbers' is count of numbers or #false for eternal pleasure.
; 'numbers' is count of numbers or #false for eternal pleasure.
(define (pi numbers)
(define (pi numbers)
Line 4,073: Line 4,073:


(pi #false)
(pi #false)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,091: Line 4,091:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Uses the built-in Brent-Salamin arithmetic-geometric mean iteration.
Uses the built-in Brent-Salamin arithmetic-geometric mean iteration.
<lang parigp>pi()={
<syntaxhighlight lang="parigp">pi()={
my(x=Pi,n=0,t);
my(x=Pi,n=0,t);
print1("3.");
print1("3.");
Line 4,101: Line 4,101:
print1(floor(x*10^n++)%10)
print1(floor(x*10^n++)%10)
)
)
};</lang>
};</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
{{works with|Swift 4.2}}
{{works with|Swift 4.2}}
<lang swift>
<syntaxhighlight lang="swift">
//
//
// main.swift
// main.swift
Line 4,144: Line 4,144:
k = k - 14
k = k - 14
}
}
</syntaxhighlight>
</lang>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 4,150: Line 4,150:
With minor editing changes as published by Stanley Rabinowitz in [http://www.mathpropress.com/stan/bibliography/spigot.pdf].
With minor editing changes as published by Stanley Rabinowitz in [http://www.mathpropress.com/stan/bibliography/spigot.pdf].
Minor improvement of <user>Mischi</user> { speedup ~2 ( n=10000 , rumtime 4s-> 1,44s fpc 2.6.4 -O3 }, by calculating only necessary digits up to n.
Minor improvement of <user>Mischi</user> { speedup ~2 ( n=10000 , rumtime 4s-> 1,44s fpc 2.6.4 -O3 }, by calculating only necessary digits up to n.
<lang pascal>Program Pi_Spigot;
<syntaxhighlight lang="pascal">Program Pi_Spigot;
const
const
n = 1000;
n = 1000;
Line 4,213: Line 4,213:
end;
end;
writeln(predigit);
writeln(predigit);
end.</lang>
end.</syntaxhighlight>
Output:
Output:
<pre>% ./Pi_Spigot
<pre>% ./Pi_Spigot
Line 4,224: Line 4,224:
This takes a numer-of-digits argument, but we can make it large (albeit using memory and some startup time). Unlike the other two, this uses no modules and does not require bigints so is worth showing.
This takes a numer-of-digits argument, but we can make it large (albeit using memory and some startup time). Unlike the other two, this uses no modules and does not require bigints so is worth showing.


<lang perl>sub pistream {
<syntaxhighlight lang="perl">sub pistream {
my $digits = shift;
my $digits = shift;
my(@out, @a);
my(@out, @a);
Line 4,264: Line 4,264:
# We've closed the spigot. Print the remainder without rounding.
# We've closed the spigot. Print the remainder without rounding.
print join "", @out[$i-15+4 .. $digits-2], "\n";
print join "", @out[$i-15+4 .. $digits-2], "\n";
}</lang>
}</syntaxhighlight>


==== Raku spigot ====
==== Raku spigot ====
Line 4,270: Line 4,270:


{{trans|Raku}}
{{trans|Raku}}
<lang perl>use bigint try=>"GMP";
<syntaxhighlight lang="perl">use bigint try=>"GMP";
sub stream {
sub stream {
my ($next, $safe, $prod, $cons, $z, $x) = @_;
my ($next, $safe, $prod, $cons, $z, $x) = @_;
Line 4,313: Line 4,313:
$|++;
$|++;
print $pi_stream->(), '.';
print $pi_stream->(), '.';
print $pi_stream->() while 1;</lang>
print $pi_stream->() while 1;</syntaxhighlight>


==== Machin's Formula ====
==== Machin's Formula ====
Line 4,319: Line 4,319:
Here is an original Perl 5 code, using Machin's formula. Not the fastest program in the world. As with the previous code, using either Math::GMP or Math::BigInt::GMP instead of the default bigint Calc backend will make it run thousands of times faster.
Here is an original Perl 5 code, using Machin's formula. Not the fastest program in the world. As with the previous code, using either Math::GMP or Math::BigInt::GMP instead of the default bigint Calc backend will make it run thousands of times faster.


<lang Perl>use bigint try=>"GMP";
<syntaxhighlight lang="perl">use bigint try=>"GMP";


# Pi/4 = 4 arctan 1/5 - arctan 1/239
# Pi/4 = 4 arctan 1/5 - arctan 1/239
Line 4,372: Line 4,372:
$ns /= $g;
$ns /= $g;
}
}
}</lang>
}</syntaxhighlight>


==== Modules ====
==== Modules ====
While no current CPAN module does continuous printing, there are (usually fast) ways to get digits of Pi. Examples include:
While no current CPAN module does continuous printing, there are (usually fast) ways to get digits of Pi. Examples include:
{{libheader|ntheory}}
{{libheader|ntheory}}
<lang perl>
<syntaxhighlight lang="perl">
use ntheory qw/Pi/;
use ntheory qw/Pi/;
say Pi(10000);
say Pi(10000);
Line 4,396: Line 4,396:
use Math::Big qw/pi/; # Very slow
use Math::Big qw/pi/; # Very slow
say pi(10000);
say pi(10000);
</syntaxhighlight>
</lang>


=={{header|Phix}}==
=={{header|Phix}}==
I already had this golf entry to hand. Prints 2400 places, change the 8400 (derived from 2400*14/4) as needed, but I've not tested > that.
I already had this golf entry to hand. Prints 2400 places, change the 8400 (derived from 2400*14/4) as needed, but I've not tested > that.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">=</span><span style="color: #000000;">10000</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #000000;">8400</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">g</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">/</span><span style="color: #000000;">5</span><span style="color: #0000FF;">),</span><span style="color: #000000;">c</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">while</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">c</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">=</span><span style="color: #000000;">10000</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #000000;">8400</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">g</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">/</span><span style="color: #000000;">5</span><span style="color: #0000FF;">),</span><span style="color: #000000;">c</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">while</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">c</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span>
<span style="color: #000000;">b</span><span style="color: #0000FF;">=</span><span style="color: #000000;">c</span> <span style="color: #008080;">while</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">+=</span><span style="color: #000000;">f</span><span style="color: #0000FF;">[</span><span style="color: #000000;">b</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">a</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">-=</span><span style="color: #000000;">1</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">[</span><span style="color: #000000;">b</span><span style="color: #0000FF;">]=</span><span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">)</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">/</span><span style="color: #000000;">g</span><span style="color: #0000FF;">)</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">-=</span><span style="color: #000000;">1</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">-=</span><span style="color: #000000;">1</span> <span style="color: #008080;">if</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">b</span><span style="color: #0000FF;">=</span><span style="color: #000000;">c</span> <span style="color: #008080;">while</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">+=</span><span style="color: #000000;">f</span><span style="color: #0000FF;">[</span><span style="color: #000000;">b</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">a</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">-=</span><span style="color: #000000;">1</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">[</span><span style="color: #000000;">b</span><span style="color: #0000FF;">]=</span><span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">)</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">/</span><span style="color: #000000;">g</span><span style="color: #0000FF;">)</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">-=</span><span style="color: #000000;">1</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">-=</span><span style="color: #000000;">1</span> <span style="color: #008080;">if</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">d</span><span style="color: #0000FF;">*=</span><span style="color: #000000;">b</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span> <span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%04d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">+</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">/</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">-=</span><span style="color: #000000;">14</span> <span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000000;">d</span><span style="color: #0000FF;">*=</span><span style="color: #000000;">b</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span> <span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%04d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">+</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">/</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">-=</span><span style="color: #000000;">14</span> <span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
Someone was benchmarking the above against Lua, so I translated the Lua entry, and upped it to 2400 places, for a fairer test.
Someone was benchmarking the above against Lua, so I translated the Lua entry, and upped it to 2400 places, for a fairer test.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2400</span><span style="color: #0000FF;">,</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2400</span><span style="color: #0000FF;">,</span>
Line 4,441: Line 4,441:
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">predigit</span><span style="color: #0000FF;">+</span><span style="color: #008000;">'0'</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">predigit</span><span style="color: #0000FF;">+</span><span style="color: #008000;">'0'</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|Picat}}==
=={{header|Picat}}==
{{trans|Erlang}}
{{trans|Erlang}}
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
pi2(1,0,1,1,3,3,0),
pi2(1,0,1,1,3,3,0),
nl.
nl.
Line 4,466: Line 4,466:
end
end
end,
end,
nl.</lang>
nl.</syntaxhighlight>


{{out}}
{{out}}
Line 4,487: Line 4,487:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
The following script uses the spigot algorithm published by Jeremy Gibbons. Hit Ctrl-C to stop it.
The following script uses the spigot algorithm published by Jeremy Gibbons. Hit Ctrl-C to stop it.
<lang PicoLisp>#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
<syntaxhighlight lang="picolisp">#!/usr/bin/picolisp /usr/lib/picolisp/lib.l


(de piDigit ()
(de piDigit ()
Line 4,507: Line 4,507:
(loop
(loop
(prin (piDigit))
(prin (piDigit))
(flush) )</lang>
(flush) )</syntaxhighlight>
Output:
Output:
<pre>3.14159265358979323846264338327950288419716939937510582097494459 ...</pre>
<pre>3.14159265358979323846264338327950288419716939937510582097494459 ...</pre>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>/* Uses the algorithm of S. Rabinowicz and S. Wagon, "A Spigot Algorithm */
<syntaxhighlight lang="pl/i">/* Uses the algorithm of S. Rabinowicz and S. Wagon, "A Spigot Algorithm */
/* for the Digits of Pi". */
/* for the Digits of Pi". */
(subrg, fofl, size):
(subrg, fofl, size):
Line 4,553: Line 4,553:
put edit(predigit) (f(1));
put edit(predigit) (f(1));
end; /* of begin block */
end; /* of begin block */
end Pi_Spigot;</lang>
end Pi_Spigot;</syntaxhighlight>
output:
output:
<pre>
<pre>
Line 4,575: Line 4,575:
With some tweaking.
With some tweaking.
Prints 100 digits a time. Total possible output limited by available memory.
Prints 100 digits a time. Total possible output limited by available memory.
<lang powershell>
<syntaxhighlight lang="powershell">
Function Get-Pi ( $Digits )
Function Get-Pi ( $Digits )
{
{
Line 4,633: Line 4,633:
}
}
}
}
</syntaxhighlight>
</lang>


Alternate version using .Net classes
Alternate version using .Net classes
<lang powershell>
<syntaxhighlight lang="powershell">
[math]::pi
[math]::pi
</syntaxhighlight>
</lang>
Outputs:
Outputs:
<lang>.Net digits of pi
<syntaxhighlight lang="text">.Net digits of pi
3.14159265358979
3.14159265358979
</syntaxhighlight>
</lang>


=={{header|Prolog}}==
=={{header|Prolog}}==
Using coroutine with freeze/2 predicate:
Using coroutine with freeze/2 predicate:


<syntaxhighlight lang="prolog">
<lang Prolog>
pi_spigot :-
pi_spigot :-
pi(X),
pi(X),
Line 4,666: Line 4,666:
I2 is I + 1,
I2 is I + 1,
pi(Q2, R2, T2, I2, OUT_)
pi(Q2, R2, T2, I2, OUT_)
; true)).</lang>
; true)).</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
Calculate Pi, limited to ~24 M-digits for memory and speed reasons.
Calculate Pi, limited to ~24 M-digits for memory and speed reasons.
<lang PureBasic>#SCALE = 10000
<syntaxhighlight lang="purebasic">#SCALE = 10000
#ARRINT= 2000
#ARRINT= 2000


Line 4,709: Line 4,709:
Ctrl:
Ctrl:
PrintN(#CRLF$+"Ctrl-C was pressed")
PrintN(#CRLF$+"Ctrl-C was pressed")
End</lang>
End</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang Python>def calcPi():
<syntaxhighlight lang="python">def calcPi():
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
while True:
while True:
Line 4,737: Line 4,737:
sys.stdout.write(str(d))
sys.stdout.write(str(d))
i += 1
i += 1
if i == 40: print(""); i = 0</lang>output
if i == 40: print(""); i = 0</syntaxhighlight>output
<pre>
<pre>
3141592653589793238462643383279502884197
3141592653589793238462643383279502884197
Line 4,757: Line 4,757:


Quackery does not have variables, it has ancillary stacks. To expedite translation from Oforth, the first two definitions implement words equivalent to the [https://forth-standard.org/standard/core/VALUE Forth words VALUE and TO].
Quackery does not have variables, it has ancillary stacks. To expedite translation from Oforth, the first two definitions implement words equivalent to the [https://forth-standard.org/standard/core/VALUE Forth words VALUE and TO].
<lang Quackery> [ immovable
<syntaxhighlight lang="quackery"> [ immovable
]this[ share ]done[ ] is value ( --> x )
]this[ share ]done[ ] is value ( --> x )
Line 4,788: Line 4,788:
L 2 + to L
L 2 + to L
K 1+ to K ]
K 1+ to K ]
chcount again ]</lang>
chcount again ]</syntaxhighlight>


{{out}}
{{out}}
Line 4,811: Line 4,811:


=={{header|R}}==
=={{header|R}}==
<lang rsplus>
<syntaxhighlight lang="rsplus">
suppressMessages(library(gmp))
suppressMessages(library(gmp))
ONE <- as.bigz("1")
ONE <- as.bigz("1")
Line 4,862: Line 4,862:
}
}
cat("\n")
cat("\n")
</syntaxhighlight>
</lang>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 4,884: Line 4,884:
Utilizing Jeremy Gibbons spigot algorithm and racket generator:
Utilizing Jeremy Gibbons spigot algorithm and racket generator:


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(require racket/generator)
(require racket/generator)
Line 4,904: Line 4,904:
(when (zero? i) (display "." ))
(when (zero? i) (display "." ))
(when (zero? (modulo i 80)) (newline)))
(when (zero? (modulo i 80)) (newline)))
</syntaxhighlight>
</lang>


Output:
Output:


<lang>
<syntaxhighlight lang="text">
3.14159265358979323846264338327950288419716939937510...
3.14159265358979323846264338327950288419716939937510...
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{Works with|rakudo|2018.10}}
{{Works with|rakudo|2018.10}}
<lang perl6># based on http://www.mathpropress.com/stan/bibliography/spigot.pdf
<syntaxhighlight lang="raku" line># based on http://www.mathpropress.com/stan/bibliography/spigot.pdf


sub stream(&next, &safe, &prod, &cons, $z is copy, @x) {
sub stream(&next, &safe, &prod, &cons, $z is copy, @x) {
Line 4,947: Line 4,947:
print $pi[$i];
print $pi[$i];
once print '.'
once print '.'
}</lang>
}</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 4,980: Line 4,980:
└─ ─┘
└─ ─┘
</pre>
</pre>
<lang rexx>/*REXX program spits out decimal digits of pi (one digit at a time) until Ctrl─Break.*/
<syntaxhighlight lang="rexx">/*REXX program spits out decimal digits of pi (one digit at a time) until Ctrl─Break.*/
parse arg digs oFID . /*obtain optional argument from the CL.*/
parse arg digs oFID . /*obtain optional argument from the CL.*/
if digs=='' | digs=="," then digs= 1e6 /*Not specified? Then use the default.*/
if digs=='' | digs=="," then digs= 1e6 /*Not specified? Then use the default.*/
Line 5,008: Line 5,008:
say /*stick a fork in it, we're all done. */
say /*stick a fork in it, we're all done. */
exit: say; say n%2+1 'iterations took' format(time("Elapsed"),,2) 'seconds.'; exit 0
exit: say; say n%2+1 'iterations took' format(time("Elapsed"),,2) 'seconds.'; exit 0
halt: say; say 'PI_SPIT halted via use of Ctrl─Break.'; signal exit /*show iterations.*/</lang>
halt: say; say 'PI_SPIT halted via use of Ctrl─Break.'; signal exit /*show iterations.*/</syntaxhighlight>
{{out|output|text=&nbsp; [until the &nbsp; Ctrl─Break &nbsp; key (or equivalent) was pressed]:}}
{{out|output|text=&nbsp; [until the &nbsp; Ctrl─Break &nbsp; key (or equivalent) was pressed]:}}


Line 5,029: Line 5,029:


This algorithm is limited to the number of decimal digits as specified with the &nbsp; '''numeric digits ddd''' &nbsp; &nbsp; (line or statement six).
This algorithm is limited to the number of decimal digits as specified with the &nbsp; '''numeric digits ddd''' &nbsp; &nbsp; (line or statement six).
<lang rexx>/*REXX program spits out decimal digits of pi (one digit at a time) until Ctrl-Break.*/
<syntaxhighlight lang="rexx">/*REXX program spits out decimal digits of pi (one digit at a time) until Ctrl-Break.*/
signal on halt /*───► HALT when Ctrl─Break is pressed.*/
signal on halt /*───► HALT when Ctrl─Break is pressed.*/
parse arg digs oFID . /*obtain optional argument from the CL.*/
parse arg digs oFID . /*obtain optional argument from the CL.*/
Line 5,060: Line 5,060:
end /*forever*/
end /*forever*/
exit /*stick a fork in it, we're all done. */
exit /*stick a fork in it, we're all done. */
halt: say; say 'PI_SPIT2 halted via use of Ctrl-Break.'; exit</lang> <br><br>
halt: say; say 'PI_SPIT2 halted via use of Ctrl-Break.'; exit</syntaxhighlight> <br><br>


=={{header|Ruby}}==
=={{header|Ruby}}==
{{trans|Icon}}
{{trans|Icon}}
<lang ruby>pi_digits = Enumerator.new do |y|
<syntaxhighlight lang="ruby">pi_digits = Enumerator.new do |y|
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
loop do
loop do
Line 5,087: Line 5,087:


print pi_digits.next, "."
print pi_digits.next, "."
loop { print pi_digits.next }</lang>
loop { print pi_digits.next }</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang Rust>use num_bigint::BigInt;
<syntaxhighlight lang="rust">use num_bigint::BigInt;


fn main() {
fn main() {
Line 5,127: Line 5,127:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>object Pi {
<syntaxhighlight lang="scala">object Pi {
class PiIterator extends Iterable[BigInt] {
class PiIterator extends Iterable[BigInt] {
var r: BigInt = 0
var r: BigInt = 0
Line 5,165: Line 5,165:
}
}


}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>3.141592653589793238462643383279502884197169399375105820974944592307816406286208998
<pre>3.141592653589793238462643383279502884197169399375105820974944592307816406286208998
Line 5,173: Line 5,173:


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scala>
<syntaxhighlight lang="scala">
(import (rnrs))
(import (rnrs))


Line 5,204: Line 5,204:
(newline)
(newline)
(set! i 0))))))
(set! i 0))))))
</syntaxhighlight>
</lang>
Output:
Output:
<pre>3141592653589793238462643383279502884197
<pre>3141592653589793238462643383279502884197
Line 5,225: Line 5,225:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
include "bigint.s7i";


Line 5,263: Line 5,263:
end if;
end if;
end while;
end while;
end func;</lang>
end func;</syntaxhighlight>


Original source: [http://seed7.sourceforge.net/algorith/math.htm#pi_spigot_algorithm]
Original source: [http://seed7.sourceforge.net/algorith/math.htm#pi_spigot_algorithm]
Line 5,269: Line 5,269:
=={{header|Sidef}}==
=={{header|Sidef}}==
===Classical Algorithm===
===Classical Algorithm===
<lang ruby>func pi(callback) {
<syntaxhighlight lang="ruby">func pi(callback) {
var (q, r, t, k, n, l) = (1, 0, 1, 1, 3, 3)
var (q, r, t, k, n, l) = (1, 0, 1, 1, 3, 3)
loop {
loop {
Line 5,294: Line 5,294:
 
 
STDOUT.autoflush(true)
STDOUT.autoflush(true)
pi(func(digit){ print digit })</lang>
pi(func(digit){ print digit })</syntaxhighlight>


===Quicker, Unverified Algorithm===
===Quicker, Unverified Algorithm===
{{trans|Haskell}}
{{trans|Haskell}}
From the same .pdf mentioned throughout this task, from the last page. The original algorithm was written in Haskell, this is a translation which has also been optimized to avoid redundant multiplications. Same output, but the algorithm is based on one of Gosper’s series that yields more than one digit per term on average, so no test is made partway through the iteration. This is capable of producing approximately 100,000 digits at [https://tio.run/##Hc@9boNAEATg3k@xnXfvNjaXcEkUa7v0KeLU0fkwP7Zl4DgiIYtnJ4A0xTTfSNNV2Tmfpry/e2jQEzzgzwVsOXDkgi9c8pUdn3ggEEDD5j3h1zU2ZZOssfxCG4BbXTez9zgItgqdluc3Am1VoP3eqkgH6KKLlYffecvjdrddGEAQkygstFy02JTUok9znXGAp2GVrZJSy1VLmhwgKilghHHzffz8@jnuXB/r/NZ3JRr6aHB5gxk9mlDdI2QjTdM/ tio.run] in the maximum 60 seconds allowed.
From the same .pdf mentioned throughout this task, from the last page. The original algorithm was written in Haskell, this is a translation which has also been optimized to avoid redundant multiplications. Same output, but the algorithm is based on one of Gosper’s series that yields more than one digit per term on average, so no test is made partway through the iteration. This is capable of producing approximately 100,000 digits at [https://tio.run/##Hc@9boNAEATg3k@xnXfvNjaXcEkUa7v0KeLU0fkwP7Zl4DgiIYtnJ4A0xTTfSNNV2Tmfpry/e2jQEzzgzwVsOXDkgi9c8pUdn3ggEEDD5j3h1zU2ZZOssfxCG4BbXTez9zgItgqdluc3Am1VoP3eqkgH6KKLlYffecvjdrddGEAQkygstFy02JTUok9znXGAp2GVrZJSy1VLmhwgKilghHHzffz8@jnuXB/r/NZ3JRr6aHB5gxk9mlDdI2QjTdM/ tio.run] in the maximum 60 seconds allowed.
<lang ruby>func p(c) { var(q,r,t,g,j,h,k,a,b,y) = (1,180,60,60,54,10,10,15,3)
<syntaxhighlight lang="ruby">func p(c) { var(q,r,t,g,j,h,k,a,b,y) = (1,180,60,60,54,10,10,15,3)
loop { c(y=(q*(a+=27) +5*r)//5*t); static _ = c('.')
loop { c(y=(q*(a+=27) +5*r)//5*t); static _ = c('.')
r=10*(g+=j+=54)*(q*(b+=5) +r -y*t); q*=h+=k+=40; t*=g } }
r=10*(g+=j+=54)*(q*(b+=5) +r -y*t); q*=h+=k+=40; t*=g } }
STDOUT.autoflush(1):p(func(d){print d})</lang>
STDOUT.autoflush(1):p(func(d){print d})</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>CLASS BIGNUM;
<syntaxhighlight lang="simula">CLASS BIGNUM;
BEGIN
BEGIN


Line 5,613: Line 5,613:
TMOD :- TDIVMOD(A, B).MOD;
TMOD :- TDIVMOD(A, B).MOD;


END BIGNUM;</lang><lang simula>EXTERNAL CLASS BIGNUM;
END BIGNUM;</syntaxhighlight><syntaxhighlight lang="simula">EXTERNAL CLASS BIGNUM;
BIGNUM
BIGNUM
BEGIN
BEGIN
Line 5,682: Line 5,682:


CALCPI;
CALCPI;
END.</lang>
END.</syntaxhighlight>
Output:
Output:
<pre>3141592653589793238462643383279502884197
<pre>3141592653589793238462643383279502884197
Line 5,705: Line 5,705:
Used the compact algorithm from [https://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf Gibbons paper].
Used the compact algorithm from [https://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf Gibbons paper].
Tailspin will at some point have arbitrary precision integers, currently we have to link into java and use BigInteger. Using java code can be slightly awkward as the argument in Tailspin comes before the method, so divide and subtract read backwards.
Tailspin will at some point have arbitrary precision integers, currently we have to link into java and use BigInteger. Using java code can be slightly awkward as the argument in Tailspin comes before the method, so divide and subtract read backwards.
<lang tailspin>
<syntaxhighlight lang="tailspin">
use 'java:java.math' stand-alone
use 'java:java.math' stand-alone


Line 5,744: Line 5,744:


1 -> g&{q:$one, r:$zero, t:$one, k:$one, n:$three, l:$three} -> !VOID
1 -> g&{q:$one, r:$zero, t:$one, k:$one, n:$three, l:$three} -> !VOID
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 5,753: Line 5,753:
Based on the reference in the [[#D|D]] code.
Based on the reference in the [[#D|D]] code.
{{works with|Tcl|8.6}}
{{works with|Tcl|8.6}}
<lang tcl>package require Tcl 8.6
<syntaxhighlight lang="tcl">package require Tcl 8.6


# http://www.cut-the-knot.org/Curriculum/Algorithms/SpigotForPi.shtml
# http://www.cut-the-knot.org/Curriculum/Algorithms/SpigotForPi.shtml
Line 5,783: Line 5,783:
}
}
}
}
}</lang>
}</syntaxhighlight>
The pi digit generation requires picking a limit to the number of digits; the bigger the limit, the more digits can be ''safely'' computed. A value of 10k yields values relatively rapidly.
The pi digit generation requires picking a limit to the number of digits; the bigger the limit, the more digits can be ''safely'' computed. A value of 10k yields values relatively rapidly.
<lang tcl>coroutine piDigit piDigitsBySpigot 10000
<syntaxhighlight lang="tcl">coroutine piDigit piDigitsBySpigot 10000
fconfigure stdout -buffering none
fconfigure stdout -buffering none
while 1 {
while 1 {
puts -nonewline [piDigit]
puts -nonewline [piDigit]
}</lang>
}</syntaxhighlight>


=={{header|TypeScript}}==
=={{header|TypeScript}}==
<lang javascript>type AnyWriteableObject={write:((textToOutput:string)=>any)};
<syntaxhighlight lang="javascript">type AnyWriteableObject={write:((textToOutput:string)=>any)};


function calcPi(pipe:AnyWriteableObject) {
function calcPi(pipe:AnyWriteableObject) {
Line 5,816: Line 5,816:
}
}


calcPi(process.stdout);</lang>
calcPi(process.stdout);</syntaxhighlight>


'''Notes:'''
'''Notes:'''
Line 5,826: Line 5,826:
=== Async version ===
=== Async version ===


<lang javascript>type AnyWriteableObject = {write:((textToOutput:string)=>Promise<any>)};
<syntaxhighlight lang="javascript">type AnyWriteableObject = {write:((textToOutput:string)=>Promise<any>)};


async function calcPi<T extends AnyWriteableObject>(pipe:T) {
async function calcPi<T extends AnyWriteableObject>(pipe:T) {
Line 5,865: Line 5,865:
});
});


console.log('.'); //start!</lang>
console.log('.'); //start!</syntaxhighlight>


Here the calculation does not continue if the consumer does not consume the character.
Here the calculation does not continue if the consumer does not consume the character.
Line 5,875: Line 5,875:
{{works with|VBA|6.5}}
{{works with|VBA|6.5}}
{{works with|VBA|7.1}}
{{works with|VBA|7.1}}
<lang vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit


Sub Main()
Sub Main()
Line 5,909: Line 5,909:
End If
End If
Next n
Next n
End Sub</lang>
End Sub</syntaxhighlight>
{{out}}
{{out}}
<pre>3.
<pre>3.
Line 5,936: Line 5,936:
{{trans|C#}}
{{trans|C#}}
Don't forget to use the "'''Project'''" tab, "'''Add Reference...'''" for '''''System.Numerics''''' (in case you get compiler errors in the Visual Studio IDE)
Don't forget to use the "'''Project'''" tab, "'''Add Reference...'''" for '''''System.Numerics''''' (in case you get compiler errors in the Visual Studio IDE)
<syntaxhighlight lang=vbnet>Imports System
<syntaxhighlight lang="vbnet">Imports System
Imports System.Numerics
Imports System.Numerics
Line 5,965: Line 5,965:
===Quicker, unverified algo===
===Quicker, unverified algo===
There seems to be another algorithm in the original reference article (see the [http://www.rosettacode.org/wiki/Pi#Ada Ada] entry), which produces output a bit faster. However, the math behind the algorithm has not been completely proven. It's faster because it doesn't calculate whether each digit is accumulated properly before squirting it out. When using (slow) arbitrary precision libraries, this avoids a lot of computation time.
There seems to be another algorithm in the original reference article (see the [http://www.rosettacode.org/wiki/Pi#Ada Ada] entry), which produces output a bit faster. However, the math behind the algorithm has not been completely proven. It's faster because it doesn't calculate whether each digit is accumulated properly before squirting it out. When using (slow) arbitrary precision libraries, this avoids a lot of computation time.
<syntaxhighlight lang=vbnet>Imports System, System.Numerics, System.Text
<syntaxhighlight lang="vbnet">Imports System, System.Numerics, System.Text
Module Module1
Module Module1
Line 6,009: Line 6,009:
{{trans|Kotlin}}
{{trans|Kotlin}}
{{libheader|Wren-big}}
{{libheader|Wren-big}}
<syntaxhighlight lang=ecmascript>import "/big" for BigInt
<syntaxhighlight lang="ecmascript">import "/big" for BigInt
import "io" for Stdout
import "io" for Stdout


Line 6,056: Line 6,056:
=={{header|Yabasic}}==
=={{header|Yabasic}}==
{{trans|BASIC256}}
{{trans|BASIC256}}
<syntaxhighlight lang=yabasic>n = 1000
<syntaxhighlight lang="yabasic">n = 1000
long = 10 * int(n / 4)
long = 10 * int(n / 4)
needdecimal = 1 //true
needdecimal = 1 //true
Line 6,122: Line 6,122:
Uses the GMP big int library.
Uses the GMP big int library.
Same algorithm as many of the others on this page. Uses in place ops to cut down on big int generation (eg add vs +). Unless GC is given some hints, it will use up 16 gig quickly as it outruns the garbage collector.
Same algorithm as many of the others on this page. Uses in place ops to cut down on big int generation (eg add vs +). Unless GC is given some hints, it will use up 16 gig quickly as it outruns the garbage collector.
<syntaxhighlight lang=zkl>var [const] BN=Import("zklBigNum"),
<syntaxhighlight lang="zkl">var [const] BN=Import("zklBigNum"),
one=BN(1), two=BN(2), three=BN(3), four=BN(4), seven=BN(7), ten=BN(10);
one=BN(1), two=BN(2), three=BN(3), four=BN(4), seven=BN(7), ten=BN(10);