Jump to content

Pi: Difference between revisions

2,952 bytes added ,  1 year ago
m
syntax highlighting fixup automation
(→‎Crystal: Updated syntaxhighlight lang=, etc...)
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.
<langsyntaxhighlight lang="360asm">* Spigot algorithm do the digits of PI 02/07/2016
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</langsyntaxhighlight>
{{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:
<langsyntaxhighlight Adalang="ada">with Ada.Command_Line;
with Ada.Text_IO;
with GNU_Multiple_Precision.Big_Integers;
Line 317:
end if;
Print_Pi (N);
end Pi_Digits;</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #
 
INT base := 10;
Line 377:
# OD #);
print(new line)
)</langsyntaxhighlight>
Output:
<pre>
Line 385:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">q: 1
r: 0
t: 1
Line 421:
r: nr
]
]</langsyntaxhighlight>
 
{{out}}
Line 455:
{{libheader|MPL}}
Could be optimized with Ipp functions, but runs fast enough for me as-is. Does not work in AHKLx64.
<langsyntaxhighlight lang="autohotkey">#NoEnv
#SingleInstance, Force
SetBatchLines, -1
Line 520:
, MP_CPY(r, nr)
}
}</langsyntaxhighlight>
 
=={{header|BASIC}}==
 
==={{header|Applesoft}}===
<langsyntaxhighlight lang="basic">10 REM ADOPTED FROM COMMODORE BASIC
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
30 LN = INT(10*N/3)+16
Line 577:
550 RETURN
</syntaxhighlight>
</lang>
 
==={{header|Atari 8-bit}}===
<langsyntaxhighlight lang="basic">10 REM ADOPTED FROM COMMODORE BASIC
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>
</lang>
 
 
==={{header|BASIC256}}===
{{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
Line 694:
print d;
end if
return</langsyntaxhighlight>
 
Output:
Line 704:
This works with Commodore Basic V2
 
<langsyntaxhighlight lang="basic">10 PRINT CHR$(147)
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>
</lang>
 
==={{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.
 
<langsyntaxhighlight lang="basic"> 10 REM PI CALCULATION WITH SPIGOT
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>
</lang>
 
==={{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...
 
<langsyntaxhighlight lang="basic">10 REM ADOPTED FROM COMMODORE BASIC
15 CR=0
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
Line 865:
530 ND = 0
550 RETURN
</syntaxhighlight>
</lang>
 
==={{header|TRS-80 Model 4 BASIC}}===
 
<langsyntaxhighlight lang="basic"> 10 REM ADOPTED FROM COMMODORE 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>
</lang>
 
=={{header|BBC BASIC}}==
===BASIC version===
<langsyntaxhighlight lang="bbcbasic"> WIDTH 80
M% = (HIMEM-END-1000) / 4
DIM B%(M%)
Line 946:
E% = D% MOD 100 : L% = 2
ENDCASE
NEXT</langsyntaxhighlight>
 
===Assembler version===
{{works with|BBC BASIC for Windows}}
The first 250,000 digits output have been verified.
<langsyntaxhighlight lang="bbcbasic"> DIM P% 32
[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</langsyntaxhighlight>
'''Output:'''
<pre>
Line 996:
{{works with|GNU bc}}
{{works with|OpenBSD bc}}
<langsyntaxhighlight lang="bc">#!/usr/bin/bc -l
 
scaleinc= 20
Line 1,025:
scale= wantscale
oldpi= pi / 1
}</langsyntaxhighlight>
Output:
<pre>
Line 1,054:
=={{header|Bracmat}}==
{{trans|Icon_and_Unicon}}
<langsyntaxhighlight lang="bracmat"> ( pi
= 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)</langsyntaxhighlight>
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.
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
Line 1,218:
 
return 0;
}</langsyntaxhighlight>
 
=={{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++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
 
Line 1,421:
std::cout << *++g; // increment to the next digit and print
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,429:
=={{header|Clojure}}==
{{Trans|Python}}
<langsyntaxhighlight lang="lisp">(ns pidigits
(:gen-class))
 
Line 1,467:
(println))
(print q))
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 1,478:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun pi-spigot ()
(labels
((g (q r t1 k n l)
Line 1,502:
(* t1 l)))
(+ l 2))))))
(g 1 0 1 1 3 3)))</langsyntaxhighlight>
{{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
<langsyntaxhighlight lang="delphi">
unit Pi_BBC_Main;
 
Line 1,794:
 
end.
</syntaxhighlight>
</lang>
{{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.
<langsyntaxhighlight lang="edsac">
[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>
</lang>
{{out}}
<pre>
Line 2,041:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Pi do
def calc, do: calc(1,0,1,1,3,3,0)
Line 2,057:
end
 
Pi.calc</langsyntaxhighlight>
 
{{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}}
<langsyntaxhighlight lang="factor">USING: combinators.extras io kernel locals math prettyprint ;
IN: rosetta-code.pi
 
Line 2,188:
] forever ;
 
MAIN: calc-pi-digits</langsyntaxhighlight>
 
=={{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">
<lang Fortran>
program pi
implicit none
Line 2,214:
write (*,'(i2,"."/(1x,10i5.5))') buffer
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.
<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">
<lang Fortran>
!================================================
program pi_spigot_unbounded
Line 2,291:
 
end program
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
{{libheader|GMP}}
<langsyntaxhighlight lang="freebasic">' version 05-07-2018
' compile with: fbc -s console
 
Line 2,348:
mpz_set(r, tmp2)
End If
Loop</langsyntaxhighlight>
{{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.
 
<langsyntaxhighlight lang="funl">def compute_pi =
def g( q, r, t, k, n, l ) =
if 4*q + r - t < n*t
Line 2,385:
print( d )
 
println()</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="futurebasic">
 
_maxlong = 0x7fffffff
Line 2,559:
 
HandleEvents
</syntaxhighlight>
</lang>
 
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.)
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,723:
}
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
{{trans|Java}}
Solution:
<langsyntaxhighlight lang="groovy">BigInteger q = 1, r = 0, t = 1, k = 1, n = 3, l = 3
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
}</langsyntaxhighlight>
 
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]:
<langsyntaxhighlight lang="haskell">pi_ = g (1, 0, 1, 1, 3, 3)
where
g (q, r, t, k, n, l) =
Line 2,762:
, k + 1
, div (q * (7 * k + 2) + r * l) (t * l)
, l + 2)</langsyntaxhighlight>
 
===Complete command-line program===
Line 2,768:
{{Works with|GHC|7.4.1}}
 
<langsyntaxhighlight lang="haskell">#!/usr/bin/runhaskell
 
import Control.Monad
Line 2,785:
main = do
hSetBuffering stdout $ BlockBuffering $ Just 80
forM_ digs putChar</langsyntaxhighlight>
 
{{out}}
Line 2,794:
===Quicker, Unverified Algorithm ===
Snippet verbatim from source .pdf:
<langsyntaxhighlight Haskelllang="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))
in y : g(10*q*i*(2*i-1),10*u*(q*(5*i-2)+r-y*t),t*u,i+1)</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="icon">procedure pi (q, r, t, k, n, l)
first := "yes"
repeat { # infinite loop
Line 2,830:
procedure main ()
every (writes (pi (1,0,1,1,3,3)))
end</langsyntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight lang="j">pi=: 3 :0
echo"0 '3.1'
i=. 0
Line 2,839:
echo -/ 1 10 * <.@o. 10x ^ 1 0 + i
end.
)</langsyntaxhighlight>
Example use:
<langsyntaxhighlight lang="j"> pi''
3
.
Line 2,853:
5
3
...</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|Icon}}
<langsyntaxhighlight lang="java">import java.math.BigInteger ;
 
public class Pi {
Line 2,901:
p.calcPiDigits() ;
}
}</langsyntaxhighlight>
 
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('.'); }
}</langsyntaxhighlight>
 
=== 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
 
<langsyntaxhighlight 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>
<script async defer>
Line 2,973:
calcPi();
</script>
</body></html></langsyntaxhighlight>
 
=== Web Page using BigInt ===
Line 2,979:
Above converted to use BigInt
 
<langsyntaxhighlight lang="html"><html>
<head>
</head>
Line 3,026:
</script>
</body>
</html></langsyntaxhighlight>
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;
}</langsyntaxhighlight>
 
=={{header|jq}}==
Line 3,069:
spigot grow very slightly more than linearly.
 
<langsyntaxhighlight lang="jq"># The Gibbons spigot, in the mold of the [[#Groovy]] and [[#Python]] programs shown on this page.
# The "bigint" functions needed are:
# long_minus long_add long_multiply long_div
Line 3,127:
;
 
pi_spigot</langsyntaxhighlight>
{{out}}
<div style="overflow:scroll; height:200px;">
<langsyntaxhighlight lang="sh">$ jq -M -n -c -f pi.bigint.jq
[0,9,"3"]
[1,14,"1"]
Line 3,435:
[302,8623,"2"]
...
</langsyntaxhighlight></div>
 
=={{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:
<langsyntaxhighlight lang="julia">let prec = precision(BigFloat), spi = "", digit = 1
while true
if digit > lastindex(spi)
Line 3,449:
digit += 1
end
end</langsyntaxhighlight>
 
Output:
Line 3,456:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.math.BigInteger
Line 3,500:
}
 
fun main(args: Array<String>) = calcPi()</langsyntaxhighlight>
 
{{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].
<langsyntaxhighlight Lassolang="lasso">#!/usr/bin/lasso9
define generatePi => {
Line 3,539:
loop(200) => {
stdout(#pi_digits())
}</langsyntaxhighlight>
Output (first 100 places):
<pre>3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067
Line 3,546:
=={{header|Liberty BASIC}}==
Pretty slow if you run for over 100 digits...
<langsyntaxhighlight lang="lb"> ndigits = 0
 
q = 1
Line 3,580:
wend
 
end</langsyntaxhighlight>
<pre>
3.141592653589793238462643383279502884197
Line 3,589:
=={{header|Lua}}==
{{trans|Pascal}}
<langsyntaxhighlight lang="lua">a = {}
n = 1000
len = math.modf( 10 * n / 3 )
Line 3,629:
end
end
print( predigit )</langsyntaxhighlight>
<pre>03141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086 ...</pre>
 
Line 3,639:
 
 
<syntaxhighlight lang="m2000 interpreter">
<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>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
User can interrupt computation using "Alt+." or "Cmd+." on a Mac.
<langsyntaxhighlight Mathematicalang="mathematica">WriteString[$Output, "3."];
For[i = -1, True, i--,
WriteString[$Output, RealDigits[Pi, 10, 1, i][[1, 1]]]; Pause[.05]];</langsyntaxhighlight>
 
=={{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 MATLAB="matlab">pi</langsyntaxhighlight>
<pre>
>> pi
Line 3,761:
=={{header|Nanoquery}}==
{{trans|Java}}
<langsyntaxhighlight Nanoquerylang="nanoquery">q = 1; r = 0; t = 1
k = 1; n = 3; l = 3
 
Line 3,788:
r = nr
end if
end while</langsyntaxhighlight>
{{out}}
<pre>
Line 3,796:
=={{header|NetRexx}}==
{{trans|Java}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
import java.math.BigInteger
Line 3,858:
method isFalse() private static returns boolean
return \isTrue()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,866:
=={{header|Nim}}==
{{libheader|bigints}}
<langsyntaxhighlight lang="nim">import bigints
 
var
Line 3,911:
echo ""
i = 0
eliminateDigit d</langsyntaxhighlight>
 
{{out}}
Line 3,923:
{{trans|D}}
{{libheader|bignum}}
<langsyntaxhighlight Nimlang="nim">import bignum
 
proc calcPi() =
Line 3,954:
r = nr
 
calcPi()</langsyntaxhighlight>
 
{{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.
<langsyntaxhighlight OCamllang="ocaml">open Creal;;
 
let block = 100 in
Line 3,976:
flush stdout;
incr counter
done</langsyntaxhighlight>
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].
<langsyntaxhighlight OCamllang="ocaml">open Num
 
(* series for: c*atan(1/k) *)
Line 4,020:
incr npr; shift := !shift */ base;
) else (acc := !acc */ d_acc);
done</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: calcPiDigits
| q r t k n l |
1 ->q 0 ->r 1 ->t 1 ->k 3 ->n 3 -> l
Line 4,043:
k 1+ ->k
]
] ;</langsyntaxhighlight>
 
=={{header|Ol}}==
{{trans|Scheme}}
 
<langsyntaxhighlight lang="scheme">
; 'numbers' is count of numbers or #false for eternal pleasure.
(define (pi numbers)
Line 4,073:
 
(pi #false)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,091:
=={{header|PARI/GP}}==
Uses the built-in Brent-Salamin arithmetic-geometric mean iteration.
<langsyntaxhighlight lang="parigp">pi()={
my(x=Pi,n=0,t);
print1("3.");
Line 4,101:
print1(floor(x*10^n++)%10)
)
};</langsyntaxhighlight>
 
=={{header|Swift}}==
{{works with|Swift 4.2}}
<langsyntaxhighlight lang="swift">
//
// main.swift
Line 4,144:
k = k - 14
}
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang="pascal">Program Pi_Spigot;
const
n = 1000;
Line 4,213:
end;
writeln(predigit);
end.</langsyntaxhighlight>
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.
 
<langsyntaxhighlight lang="perl">sub pistream {
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";
}</langsyntaxhighlight>
 
==== Raku spigot ====
Line 4,270:
 
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use bigint try=>"GMP";
sub stream {
my ($next, $safe, $prod, $cons, $z, $x) = @_;
Line 4,313:
$|++;
print $pi_stream->(), '.';
print $pi_stream->() while 1;</langsyntaxhighlight>
 
==== 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.
 
<langsyntaxhighlight Perllang="perl">use bigint try=>"GMP";
 
# Pi/4 = 4 arctan 1/5 - arctan 1/239
Line 4,372:
$ns /= $g;
}
}</langsyntaxhighlight>
 
==== Modules ====
While no current CPAN module does continuous printing, there are (usually fast) ways to get digits of Pi. Examples include:
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">
use ntheory qw/Pi/;
say Pi(10000);
Line 4,396:
use Math::Big qw/pi/; # Very slow
say pi(10000);
</syntaxhighlight>
</lang>
 
=={{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.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
Someone was benchmarking the above against Lua, so I translated the Lua entry, and upped it to 2400 places, for a fairer test.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
 
=={{header|Picat}}==
{{trans|Erlang}}
<langsyntaxhighlight Picatlang="picat">go =>
pi2(1,0,1,1,3,3,0),
nl.
Line 4,466:
end
end,
nl.</langsyntaxhighlight>
 
{{out}}
Line 4,487:
=={{header|PicoLisp}}==
The following script uses the spigot algorithm published by Jeremy Gibbons. Hit Ctrl-C to stop it.
<langsyntaxhighlight PicoLisplang="picolisp">#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
 
(de piDigit ()
Line 4,507:
(loop
(prin (piDigit))
(flush) )</langsyntaxhighlight>
Output:
<pre>3.14159265358979323846264338327950288419716939937510582097494459 ...</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">/* Uses the algorithm of S. Rabinowicz and S. Wagon, "A Spigot Algorithm */
/* for the Digits of Pi". */
(subrg, fofl, size):
Line 4,553:
put edit(predigit) (f(1));
end; /* of begin block */
end Pi_Spigot;</langsyntaxhighlight>
output:
<pre>
Line 4,575:
With some tweaking.
Prints 100 digits a time. Total possible output limited by available memory.
<langsyntaxhighlight lang="powershell">
Function Get-Pi ( $Digits )
{
Line 4,633:
}
}
</syntaxhighlight>
</lang>
 
Alternate version using .Net classes
<langsyntaxhighlight lang="powershell">
[math]::pi
</syntaxhighlight>
</lang>
Outputs:
<syntaxhighlight lang="text">.Net digits of pi
3.14159265358979
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
Using coroutine with freeze/2 predicate:
 
<syntaxhighlight lang="prolog">
<lang Prolog>
pi_spigot :-
pi(X),
Line 4,666:
I2 is I + 1,
pi(Q2, R2, T2, I2, OUT_)
; true)).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
Calculate Pi, limited to ~24 M-digits for memory and speed reasons.
<langsyntaxhighlight PureBasiclang="purebasic">#SCALE = 10000
#ARRINT= 2000
 
Line 4,709:
Ctrl:
PrintN(#CRLF$+"Ctrl-C was pressed")
End</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight Pythonlang="python">def calcPi():
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</langsyntaxhighlight>output
<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].
<langsyntaxhighlight Quackerylang="quackery"> [ immovable
]this[ share ]done[ ] is value ( --> x )
Line 4,788:
L 2 + to L
K 1+ to K ]
chcount again ]</langsyntaxhighlight>
 
{{out}}
Line 4,811:
 
=={{header|R}}==
<langsyntaxhighlight lang="rsplus">
suppressMessages(library(gmp))
ONE <- as.bigz("1")
Line 4,862:
}
cat("\n")
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 4,884:
Utilizing Jeremy Gibbons spigot algorithm and racket generator:
 
<langsyntaxhighlight lang="racket">
#lang racket
(require racket/generator)
Line 4,904:
(when (zero? i) (display "." ))
(when (zero? (modulo i 80)) (newline)))
</syntaxhighlight>
</lang>
 
Output:
 
<syntaxhighlight lang="text">
3.14159265358979323846264338327950288419716939937510...
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2018.10}}
<syntaxhighlight lang="raku" perl6line># based on http://www.mathpropress.com/stan/bibliography/spigot.pdf
 
sub stream(&next, &safe, &prod, &cons, $z is copy, @x) {
Line 4,947:
print $pi[$i];
once print '.'
}</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 4,980:
└─ ─┘
</pre>
<langsyntaxhighlight 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.*/
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.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; [until the &nbsp; Ctrl─Break &nbsp; key (or equivalent) was pressed]:}}
 
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).
<langsyntaxhighlight 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.*/
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</langsyntaxhighlight> <br><br>
 
=={{header|Ruby}}==
{{trans|Icon}}
<langsyntaxhighlight lang="ruby">pi_digits = Enumerator.new do |y|
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 }</langsyntaxhighlight>
 
=={{header|Rust}}==
{{trans|Kotlin}}
<langsyntaxhighlight Rustlang="rust">use num_bigint::BigInt;
 
fn main() {
Line 5,127:
}
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object Pi {
class PiIterator extends Iterable[BigInt] {
var r: BigInt = 0
Line 5,165:
}
 
}</langsyntaxhighlight>
Output:
<pre>3.141592653589793238462643383279502884197169399375105820974944592307816406286208998
Line 5,173:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scala">
(import (rnrs))
 
Line 5,204:
(newline)
(set! i 0))))))
</syntaxhighlight>
</lang>
Output:
<pre>3141592653589793238462643383279502884197
Line 5,225:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
 
Line 5,263:
end if;
end while;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/math.htm#pi_spigot_algorithm]
Line 5,269:
=={{header|Sidef}}==
===Classical Algorithm===
<langsyntaxhighlight lang="ruby">func pi(callback) {
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 })</langsyntaxhighlight>
 
===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.
<langsyntaxhighlight 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('.')
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})</langsyntaxhighlight>
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">CLASS BIGNUM;
BEGIN
 
Line 5,613:
TMOD :- TDIVMOD(A, B).MOD;
 
END BIGNUM;</langsyntaxhighlight><syntaxhighlight lang ="simula">EXTERNAL CLASS BIGNUM;
BIGNUM
BEGIN
Line 5,682:
 
CALCPI;
END.</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="tailspin">
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>
</lang>
{{out}}
<pre>
Line 5,753:
Based on the reference in the [[#D|D]] code.
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
# http://www.cut-the-knot.org/Curriculum/Algorithms/SpigotForPi.shtml
Line 5,783:
}
}
}</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="tcl">coroutine piDigit piDigitsBySpigot 10000
fconfigure stdout -buffering none
while 1 {
puts -nonewline [piDigit]
}</langsyntaxhighlight>
 
=={{header|TypeScript}}==
<langsyntaxhighlight lang="javascript">type AnyWriteableObject={write:((textToOutput:string)=>any)};
 
function calcPi(pipe:AnyWriteableObject) {
Line 5,816:
}
 
calcPi(process.stdout);</langsyntaxhighlight>
 
'''Notes:'''
Line 5,826:
=== Async version ===
 
<langsyntaxhighlight lang="javascript">type AnyWriteableObject = {write:((textToOutput:string)=>Promise<any>)};
 
async function calcPi<T extends AnyWriteableObject>(pipe:T) {
Line 5,865:
});
 
console.log('.'); //start!</langsyntaxhighlight>
 
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}}
<langsyntaxhighlight lang="vb">Option Explicit
 
Sub Main()
Line 5,909:
End If
Next n
End Sub</langsyntaxhighlight>
{{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);
 
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.