Pi: Difference between revisions
m
syntax highlighting fixup automation
(→Crystal: Updated syntaxhighlight lang=, etc...) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 18:
{{trans|D}}
<syntaxhighlight lang="11l">V ndigits = 0
V q = BigInt(1)
V r = BigInt(0)
Line 72:
{{trans|FORTRAN}}
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<
PISPIG CSECT
USING PISPIG,R13 base register
Line 175:
NBUF EQU 201 number of 5 decimals
NVECT EQU 3350 nvect=ceil(nbuf*50/3)
END PISPIG</
{{out}}
<pre>
Line 206:
uses same algorithm as Go solution, from http://web.comlab.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf
;pi_digits.adb:
<
with Ada.Text_IO;
with GNU_Multiple_Precision.Big_Integers;
Line 317:
end if;
Print_Pi (N);
end Pi_Digits;</
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>
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''.}}
This codes uses 33 decimals places as a test case. Performance is O(2) based on the number of decimal places required.
<
INT base := 10;
Line 377:
# OD #);
print(new line)
)</
Output:
<pre>
Line 385:
=={{header|Arturo}}==
<
r: 0
t: 1
Line 421:
r: nr
]
]</
{{out}}
Line 455:
{{libheader|MPL}}
Could be optimized with Ipp functions, but runs fast enough for me as-is. Does not work in AHKLx64.
<
#SingleInstance, Force
SetBatchLines, -1
Line 520:
, MP_CPY(r, nr)
}
}</
=={{header|BASIC}}==
==={{header|Applesoft}}===
<
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
30 LN = INT(10*N/3)+16
Line 577:
550 RETURN
</syntaxhighlight>
==={{header|Atari 8-bit}}===
<
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
30 LN = INT(10*N/3)+16
Line 631:
530 ND = 0
550 RETURN
</syntaxhighlight>
==={{header|BASIC256}}===
{{Trans|Pascal}} below, and originally published by Stanley Rabinowitz in [http://www.mathpropress.com/stan/bibliography/spigot.pdf].
<syntaxhighlight lang="basic256">cls
n =1000
Line 694:
print d;
end if
return</
Output:
Line 704:
This works with Commodore Basic V2
<
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
30 LN = INT(10*N/3)+16
Line 755:
530 ND = 0
550 RETURN
</syntaxhighlight>
==={{header|Integer Basic}}===
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.
<
100 N=100: REM MAX N=260 TO AVOID OVERFLOW
110 LEN=(10*N)/3
Line 806:
1080 IF I>0 THEN GOTO 1040
1090 RETURN
</syntaxhighlight>
==={{header|Osborne 1 MBASIC}}===
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...
<
15 CR=0
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
Line 865:
530 ND = 0
550 RETURN
</syntaxhighlight>
==={{header|TRS-80 Model 4 BASIC}}===
<
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
30 LN = INT(10*N/3)+16
Line 920:
530 ND = 0
550 RETURN
</syntaxhighlight>
=={{header|BBC BASIC}}==
===BASIC version===
<
M% = (HIMEM-END-1000) / 4
DIM B%(M%)
Line 946:
E% = D% MOD 100 : L% = 2
ENDCASE
NEXT</
===Assembler version===
{{works with|BBC BASIC for Windows}}
The first 250,000 digits output have been verified.
<
[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
Line 973:
E% = D% MOD 100 : L% = 2
ENDCASE
NEXT</
'''Output:'''
<pre>
Line 996:
{{works with|GNU bc}}
{{works with|OpenBSD bc}}
<
scaleinc= 20
Line 1,025:
scale= wantscale
oldpi= pi / 1
}</
Output:
<pre>
Line 1,054:
=={{header|Bracmat}}==
{{trans|Icon_and_Unicon}}
<
= f,q r t k n l,first
. !arg:((=?f),?q,?r,?t,?k,?n,?l)
Line 1,082:
)
)
& pi$((=.put$!arg),1,0,1,1,3,3)</
Output:
<pre>3.1415926535897932384626433832795028841971693993751058209749445923078164062
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.
<
#include <stdlib.h>
#include <gmp.h>
Line 1,218:
return 0;
}</
=={{header|C sharp|C#}}==
Line 1,224:
{{trans|Java}}
<syntaxhighlight lang="csharp">using System;
using System.Numerics;
Line 1,277:
Adopted Version:
{{libheader|System.Numerics}}
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,366:
=={{header|C++}}==
<
#include <boost/multiprecision/cpp_int.hpp>
Line 1,421:
std::cout << *++g; // increment to the next digit and print
}
}</
{{out}}
<pre>
Line 1,429:
=={{header|Clojure}}==
{{Trans|Python}}
<
(:gen-class))
Line 1,467:
(println))
(print q))
</syntaxhighlight>
{{Output}}
<pre>
Line 1,478:
=={{header|Common Lisp}}==
<
(labels
((g (q r t1 k n l)
Line 1,502:
(* t1 l)))
(+ l 2))))))
(g 1 0 1 1 3 3)))</
{{out}}
<pre>CL-USER> (pi-spigot)
Line 1,509:
=={{header|Crystal}}==
{{trans|Ruby}}
<syntaxhighlight lang="ruby">require "big"
def pi
Line 1,546:
=={{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.
<syntaxhighlight lang="d">import std.stdio, std.conv, std.string;
struct PiDigits {
Line 1,597:
534211706</pre>
===Alternative version===
<syntaxhighlight lang="d">import std.stdio, std.bigint;
void main() {
Line 1,656:
introcs dot cs dot princeton dot edu slash java slash data slash pi-10million.txt
<
unit Pi_BBC_Main;
Line 1,794:
end.
</syntaxhighlight>
{{out}}
<pre>
Line 1,810:
With only a few changes (noted in the comments), the same code can be used to
output the first 2070 digits of e.
<
[EDSAC program, Initial Orders 2.
Calculates digits of pi by spigot algorithm.
Line 2,030:
E 11 Z [define entry point]
P F [acc = 0 on entry]
</syntaxhighlight>
{{out}}
<pre>
Line 2,041:
=={{header|Elixir}}==
{{trans|Erlang}}
<
def calc, do: calc(1,0,1,1,3,3,0)
Line 2,057:
end
Pi.calc</
{{out}}
Line 2,080:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(pi_calculation).
-export([main/0]).
Line 2,141:
===Translation of Haskell===
{{trans|Haskell}}
<syntaxhighlight lang="fsharp">let rec g q r t k n l = seq {
if 4I*q+r-t < n*t
then
Line 2,160:
===As an Unfold===
Haskell can probably do this as an unfold, it has not so I shall in F#
<syntaxhighlight lang="fsharp">
// 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
Line 2,168:
=={{header|Factor}}==
{{trans|Oforth}}
<
IN: rosetta-code.pi
Line 2,188:
] forever ;
MAIN: calc-pi-digits</
=={{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".
<syntaxhighlight lang="fortran">
program pi
implicit none
Line 2,214:
write (*,'(i2,"."/(1x,10i5.5))') buffer
end program pi
</syntaxhighlight>
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>
Line 2,242:
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.
<syntaxhighlight lang="fortran">
!================================================
program pi_spigot_unbounded
Line 2,291:
end program
</syntaxhighlight>
=={{header|FreeBASIC}}==
{{libheader|GMP}}
<
' compile with: fbc -s console
Line 2,348:
mpz_set(r, tmp2)
End If
Loop</
{{out}}
<pre>3.
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.
<
def g( q, r, t, k, n, l ) =
if 4*q + r - t < n*t
Line 2,385:
print( d )
println()</
=={{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.
<
_maxlong = 0x7fffffff
Line 2,559:
HandleEvents
</syntaxhighlight>
Output:
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].
(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.)
<
import (
Line 2,723:
}
}
}</
=={{header|Groovy}}==
{{trans|Java}}
Solution:
<
String nn
boolean first = true
Line 2,737:
: ['' , first, q*k , (2*q + r)*l , t*l, k + 1, (q*(7*k + 2) + r*l)/(t*l), l + 2]
print nn
}</
Output (thru first 1000 iterations):
Line 2,744:
=={{header|Haskell}}==
The code from [http://www.cs.ox.ac.uk/people/jeremy.gibbons/publications/spigot.pdf]:
<
where
g (q, r, t, k, n, l) =
Line 2,762:
, k + 1
, div (q * (7 * k + 2) + r * l) (t * l)
, l + 2)</
===Complete command-line program===
Line 2,768:
{{Works with|GHC|7.4.1}}
<
import Control.Monad
Line 2,785:
main = do
hSetBuffering stdout $ BlockBuffering $ Just 80
forM_ digs putChar</
{{out}}
Line 2,794:
===Quicker, Unverified Algorithm ===
Snippet verbatim from source .pdf:
<
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)</
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:
=={{header|Icon}} and {{header|Unicon}}==
{{Trans|PicoLisp}} based on Jeremy Gibbons' Haskell solution.
<
first := "yes"
repeat { # infinite loop
Line 2,830:
procedure main ()
every (writes (pi (1,0,1,1,3,3)))
end</
=={{header|J}}==
<
echo"0 '3.1'
i=. 0
Line 2,839:
echo -/ 1 10 * <.@o. 10x ^ 1 0 + i
end.
)</
Example use:
<
3
.
Line 2,853:
5
3
...</
=={{header|Java}}==
{{trans|Icon}}
<
public class Pi {
Line 2,901:
p.calcPiDigits() ;
}
}</
Output :
Line 2,914:
process.stdout.write will work in Node.js; to make this work in a browser, change it to document.body.textContent += .
<syntaxhighlight lang="text">let q = 1n, r = 180n, t = 60n, i = 2n;
for (;;) {
let y = (q*(27n*i-12n)+5n*r)/(5n*t);
Line 2,924:
process.stdout.write(y.toString());
if (i === 3n) { process.stdout.write('.'); }
}</
=== Web Page version ===
Line 2,930:
This shows how to load the previous code into a webpage that writes digits out without freezing the browser
<
<body style="width: 100%"><tt id="pi"></tt><tt>...</tt>
<script async defer>
Line 2,973:
calcPi();
</script>
</body></html></
=== Web Page using BigInt ===
Line 2,979:
Above converted to use BigInt
<
<head>
</head>
Line 3,026:
</script>
</body>
</html></
Note: removing the parameters to continueCalcPi() as shown may eat (even) more memory, not entirely sure about that.
Line 3,032:
Returns an approximation of Pi.
<syntaxhighlight lang="text">var calcPi = function() {
var n = 20000;
var pi = 0;
Line 3,045:
}
return pi;
}</
=={{header|jq}}==
Line 3,069:
spigot grow very slightly more than linearly.
<
# The "bigint" functions needed are:
# long_minus long_add long_multiply long_div
Line 3,127:
;
pi_spigot</
{{out}}
<div style="overflow:scroll; height:200px;">
<
[0,9,"3"]
[1,14,"1"]
Line 3,435:
[302,8623,"2"]
...
</
=={{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:
<
while true
if digit > lastindex(spi)
Line 3,449:
digit += 1
end
end</
Output:
Line 3,456:
=={{header|Kotlin}}==
{{trans|Java}}
<
import java.math.BigInteger
Line 3,500:
}
fun main(args: Array<String>) = calcPi()</
{{out}}
Line 3,509:
=={{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].
<
define generatePi => {
Line 3,539:
loop(200) => {
stdout(#pi_digits())
}</
Output (first 100 places):
<pre>3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067
Line 3,546:
=={{header|Liberty BASIC}}==
Pretty slow if you run for over 100 digits...
<
q = 1
Line 3,580:
wend
end</
<pre>
3.141592653589793238462643383279502884197
Line 3,589:
=={{header|Lua}}==
{{trans|Pascal}}
<
n = 1000
len = math.modf( 10 * n / 3 )
Line 3,629:
end
end
print( predigit )</
<pre>03141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086 ...</pre>
Line 3,639:
<syntaxhighlight lang="m2000 interpreter">
Module Checkpi {
Module FindPi(Digits){
Line 3,735:
Modules ? ' current module exist
Stack ' Stack of values ' has to be empty, we didn't use current stack for values.
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
User can interrupt computation using "Alt+." or "Cmd+." on a Mac.
<
For[i = -1, True, i--,
WriteString[$Output, RealDigits[Pi, 10, 1, i][[1, 1]]]; Pause[.05]];</
=={{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).
<syntaxhighlight lang
<pre>
>> pi
Line 3,761:
=={{header|Nanoquery}}==
{{trans|Java}}
<
k = 1; n = 3; l = 3
Line 3,788:
r = nr
end if
end while</
{{out}}
<pre>
Line 3,796:
=={{header|NetRexx}}==
{{trans|Java}}
<
options replace format comments java crossref symbols binary
import java.math.BigInteger
Line 3,858:
method isFalse() private static returns boolean
return \isTrue()
</syntaxhighlight>
{{out}}
<pre>
Line 3,866:
=={{header|Nim}}==
{{libheader|bigints}}
<
var
Line 3,911:
echo ""
i = 0
eliminateDigit d</
{{out}}
Line 3,923:
{{trans|D}}
{{libheader|bignum}}
<
proc calcPi() =
Line 3,954:
r = nr
calcPi()</
{{out}}
Line 3,965:
=={{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.
<
let block = 100 in
Line 3,976:
flush stdout;
incr counter
done</
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].
<
(* series for: c*atan(1/k) *)
Line 4,020:
incr npr; shift := !shift */ base;
) else (acc := !acc */ d_acc);
done</
=={{header|Oforth}}==
<
| q r t k n l |
1 ->q 0 ->r 1 ->t 1 ->k 3 ->n 3 -> l
Line 4,043:
k 1+ ->k
]
] ;</
=={{header|Ol}}==
{{trans|Scheme}}
<
; 'numbers' is count of numbers or #false for eternal pleasure.
(define (pi numbers)
Line 4,073:
(pi #false)
</syntaxhighlight>
{{out}}
<pre>
Line 4,091:
=={{header|PARI/GP}}==
Uses the built-in Brent-Salamin arithmetic-geometric mean iteration.
<
my(x=Pi,n=0,t);
print1("3.");
Line 4,101:
print1(floor(x*10^n++)%10)
)
};</
=={{header|Swift}}==
{{works with|Swift 4.2}}
<
//
// main.swift
Line 4,144:
k = k - 14
}
</syntaxhighlight>
=={{header|Pascal}}==
Line 4,150:
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.
<
const
n = 1000;
Line 4,213:
end;
writeln(predigit);
end.</
Output:
<pre>% ./Pi_Spigot
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.
<
my $digits = shift;
my(@out, @a);
Line 4,264:
# We've closed the spigot. Print the remainder without rounding.
print join "", @out[$i-15+4 .. $digits-2], "\n";
}</
==== Raku spigot ====
Line 4,270:
{{trans|Raku}}
<
sub stream {
my ($next, $safe, $prod, $cons, $z, $x) = @_;
Line 4,313:
$|++;
print $pi_stream->(), '.';
print $pi_stream->() while 1;</
==== Machin's Formula ====
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.
<
# Pi/4 = 4 arctan 1/5 - arctan 1/239
Line 4,372:
$ns /= $g;
}
}</
==== Modules ====
While no current CPAN module does continuous printing, there are (usually fast) ways to get digits of Pi. Examples include:
{{libheader|ntheory}}
<
use ntheory qw/Pi/;
say Pi(10000);
Line 4,396:
use Math::Big qw/pi/; # Very slow
say pi(10000);
</syntaxhighlight>
=={{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.
<!--<
<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: #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>
<!--</
Someone was benchmarking the above against Lua, so I translated the Lua entry, and upped it to 2400 places, for a fairer test.
<!--<
<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>
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: #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>
<!--</
=={{header|Picat}}==
{{trans|Erlang}}
<
pi2(1,0,1,1,3,3,0),
nl.
Line 4,466:
end
end,
nl.</
{{out}}
Line 4,487:
=={{header|PicoLisp}}==
The following script uses the spigot algorithm published by Jeremy Gibbons. Hit Ctrl-C to stop it.
<
(de piDigit ()
Line 4,507:
(loop
(prin (piDigit))
(flush) )</
Output:
<pre>3.14159265358979323846264338327950288419716939937510582097494459 ...</pre>
=={{header|PL/I}}==
<
/* for the Digits of Pi". */
(subrg, fofl, size):
Line 4,553:
put edit(predigit) (f(1));
end; /* of begin block */
end Pi_Spigot;</
output:
<pre>
Line 4,575:
With some tweaking.
Prints 100 digits a time. Total possible output limited by available memory.
<
Function Get-Pi ( $Digits )
{
Line 4,633:
}
}
</syntaxhighlight>
Alternate version using .Net classes
<
[math]::pi
</syntaxhighlight>
Outputs:
<syntaxhighlight lang="text">.Net digits of pi
3.14159265358979
</syntaxhighlight>
=={{header|Prolog}}==
Using coroutine with freeze/2 predicate:
<syntaxhighlight lang="prolog">
pi_spigot :-
pi(X),
Line 4,666:
I2 is I + 1,
pi(Q2, R2, T2, I2, OUT_)
; true)).</
=={{header|PureBasic}}==
Calculate Pi, limited to ~24 M-digits for memory and speed reasons.
<
#ARRINT= 2000
Line 4,709:
Ctrl:
PrintN(#CRLF$+"Ctrl-C was pressed")
End</
=={{header|Python}}==
<
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
while True:
Line 4,737:
sys.stdout.write(str(d))
i += 1
if i == 40: print(""); i = 0</
<pre>
3141592653589793238462643383279502884197
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].
<
]this[ share ]done[ ] is value ( --> x )
Line 4,788:
L 2 + to L
K 1+ to K ]
chcount again ]</
{{out}}
Line 4,811:
=={{header|R}}==
<
suppressMessages(library(gmp))
ONE <- as.bigz("1")
Line 4,862:
}
cat("\n")
</syntaxhighlight>
'''Output:'''
<pre>
Line 4,884:
Utilizing Jeremy Gibbons spigot algorithm and racket generator:
<
#lang racket
(require racket/generator)
Line 4,904:
(when (zero? i) (display "." ))
(when (zero? (modulo i 80)) (newline)))
</syntaxhighlight>
Output:
<syntaxhighlight lang="text">
3.14159265358979323846264338327950288419716939937510...
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2018.10}}
<syntaxhighlight lang="raku"
sub stream(&next, &safe, &prod, &cons, $z is copy, @x) {
Line 4,947:
print $pi[$i];
once print '.'
}</
=={{header|REXX}}==
Line 4,980:
└─ ─┘
</pre>
<
parse arg digs oFID . /*obtain optional argument from the CL.*/
if digs=='' | digs=="," then digs= 1e6 /*Not specified? Then use the default.*/
Line 5,008:
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
halt: say; say 'PI_SPIT halted via use of Ctrl─Break.'; signal exit /*show iterations.*/</
{{out|output|text= [until the Ctrl─Break key (or equivalent) was pressed]:}}
Line 5,029:
This algorithm is limited to the number of decimal digits as specified with the '''numeric digits ddd''' (line or statement six).
<
signal on halt /*───► HALT when Ctrl─Break is pressed.*/
parse arg digs oFID . /*obtain optional argument from the CL.*/
Line 5,060:
end /*forever*/
exit /*stick a fork in it, we're all done. */
halt: say; say 'PI_SPIT2 halted via use of Ctrl-Break.'; exit</
=={{header|Ruby}}==
{{trans|Icon}}
<
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
loop do
Line 5,087:
print pi_digits.next, "."
loop { print pi_digits.next }</
=={{header|Rust}}==
{{trans|Kotlin}}
<
fn main() {
Line 5,127:
}
}
}</
=={{header|Scala}}==
<
class PiIterator extends Iterable[BigInt] {
var r: BigInt = 0
Line 5,165:
}
}</
Output:
<pre>3.141592653589793238462643383279502884197169399375105820974944592307816406286208998
Line 5,173:
=={{header|Scheme}}==
<
(import (rnrs))
Line 5,204:
(newline)
(set! i 0))))))
</syntaxhighlight>
Output:
<pre>3141592653589793238462643383279502884197
Line 5,225:
=={{header|Seed7}}==
<
include "bigint.s7i";
Line 5,263:
end if;
end while;
end func;</
Original source: [http://seed7.sourceforge.net/algorith/math.htm#pi_spigot_algorithm]
Line 5,269:
=={{header|Sidef}}==
===Classical Algorithm===
<
var (q, r, t, k, n, l) = (1, 0, 1, 1, 3, 3)
loop {
Line 5,294:
STDOUT.autoflush(true)
pi(func(digit){ print digit })</
===Quicker, Unverified Algorithm===
{{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.
<
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 } }
STDOUT.autoflush(1):p(func(d){print d})</
=={{header|Simula}}==
<
BEGIN
Line 5,613:
TMOD :- TDIVMOD(A, B).MOD;
END BIGNUM;</
BIGNUM
BEGIN
Line 5,682:
CALCPI;
END.</
Output:
<pre>3141592653589793238462643383279502884197
Line 5,705:
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.
<
use 'java:java.math' stand-alone
Line 5,744:
1 -> g&{q:$one, r:$zero, t:$one, k:$one, n:$three, l:$three} -> !VOID
</syntaxhighlight>
{{out}}
<pre>
Line 5,753:
Based on the reference in the [[#D|D]] code.
{{works with|Tcl|8.6}}
<
# http://www.cut-the-knot.org/Curriculum/Algorithms/SpigotForPi.shtml
Line 5,783:
}
}
}</
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.
<
fconfigure stdout -buffering none
while 1 {
puts -nonewline [piDigit]
}</
=={{header|TypeScript}}==
<
function calcPi(pipe:AnyWriteableObject) {
Line 5,816:
}
calcPi(process.stdout);</
'''Notes:'''
Line 5,826:
=== Async version ===
<
async function calcPi<T extends AnyWriteableObject>(pipe:T) {
Line 5,865:
});
console.log('.'); //start!</
Here the calculation does not continue if the consumer does not consume the character.
Line 5,875:
{{works with|VBA|6.5}}
{{works with|VBA|7.1}}
<
Sub Main()
Line 5,909:
End If
Next n
End Sub</
{{out}}
<pre>3.
Line 5,936:
{{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)
<syntaxhighlight lang="vbnet">Imports System
Imports System.Numerics
Line 5,965:
===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.
<syntaxhighlight lang="vbnet">Imports System, System.Numerics, System.Text
Module Module1
Line 6,009:
{{trans|Kotlin}}
{{libheader|Wren-big}}
<syntaxhighlight lang="ecmascript">import "/big" for BigInt
import "io" for Stdout
Line 6,056:
=={{header|Yabasic}}==
{{trans|BASIC256}}
<syntaxhighlight lang="yabasic">n = 1000
long = 10 * int(n / 4)
needdecimal = 1 //true
Line 6,122:
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.
<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);
|