Bernoulli numbers: Difference between revisions
Content added Content deleted
m (→{{header|AppleScript}}: Tidy-up, more comments, minor optimisations.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 36: | Line 36: | ||
Using a GMP thick binding available at http://www.codeforge.com/article/422541 |
Using a GMP thick binding available at http://www.codeforge.com/article/422541 |
||
< |
<syntaxhighlight lang=Ada>WITH GMP.Rationals, GMP.Integers, Ada.Text_IO, Ada.Strings.Fixed, Ada.Strings; |
||
USE GMP.Rationals, GMP.Integers, Ada.Text_IO, Ada.Strings.Fixed, Ada.Strings; |
USE GMP.Rationals, GMP.Integers, Ada.Text_IO, Ada.Strings.Fixed, Ada.Strings; |
||
Line 67: | Line 67: | ||
END IF; |
END IF; |
||
END LOOP; |
END LOOP; |
||
END Main;</ |
END Main;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 107: | Line 107: | ||
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}} |
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}} |
||
Uses the LONG LONG INT mode of Algol 68G which allows large precision integers. |
Uses the LONG LONG INT mode of Algol 68G which allows large precision integers. |
||
< |
<syntaxhighlight lang=algol68>BEGIN |
||
# Show Bernoulli numbers B0 to B60 as rational numbers # |
# Show Bernoulli numbers B0 to B60 as rational numbers # |
||
Line 184: | Line 184: | ||
OD |
OD |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 223: | Line 223: | ||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
To be able to handle numbers up to B(60) and beyond, this script represents the numbers with lists whose items are the digit values — which of course requires custom math routines. |
To be able to handle numbers up to B(60) and beyond, this script represents the numbers with lists whose items are the digit values — which of course requires custom math routines. |
||
< |
<syntaxhighlight lang=applescript>on bernoullis(n) -- Return a list of "numerator / denominator" texts representing Bernoulli numbers B(0) to B(n). |
||
set listMathScript to getListMathScript(10) -- Script object providing custom list math routines. |
set listMathScript to getListMathScript(10) -- Script object providing custom list math routines. |
||
Line 466: | Line 466: | ||
end task |
end task |
||
task()</ |
task()</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
< |
<syntaxhighlight lang=applescript>" |
||
B(0) = 1 / 1 |
B(0) = 1 / 1 |
||
B(1) = 1 / 2 |
B(1) = 1 / 2 |
||
Line 501: | Line 501: | ||
B(56) = -2479392929313226753685415739663229 / 870 |
B(56) = -2479392929313226753685415739663229 / 870 |
||
B(58) = 84483613348880041862046775994036021 / 354 |
B(58) = 84483613348880041862046775994036021 / 354 |
||
B(60) = -1215233140483755572040304994079820246041491 / 56786730"</ |
B(60) = -1215233140483755572040304994079820246041491 / 56786730"</syntaxhighlight> |
||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang=bracmat> ( BernoulliList |
||
= B Bs answer indLn indexLen indexPadding |
= B Bs answer indLn indexLen indexPadding |
||
, n numberPadding p solPos solidusPos sp |
, n numberPadding p solPos solidusPos sp |
||
Line 563: | Line 563: | ||
& str$!answer |
& str$!answer |
||
) |
) |
||
& BernoulliList$60;</ |
& BernoulliList$60;</syntaxhighlight> |
||
<pre>B(0)= 1/1 |
<pre>B(0)= 1/1 |
||
B(1)= 1/2 |
B(1)= 1/2 |
||
Line 599: | Line 599: | ||
=={{header|C}}== |
=={{header|C}}== |
||
{{libheader|GMP}} |
{{libheader|GMP}} |
||
<syntaxhighlight lang=C> |
|||
<lang C> |
|||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <gmp.h> |
#include <gmp.h> |
||
Line 651: | Line 651: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 693: | Line 693: | ||
{{libheader|Mpir.NET}} |
{{libheader|Mpir.NET}} |
||
Translation of the C implementation |
Translation of the C implementation |
||
< |
<syntaxhighlight lang=csharp> |
||
using Mpir.NET; |
using Mpir.NET; |
||
using System; |
using System; |
||
Line 747: | Line 747: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 787: | Line 787: | ||
{{libheader|MathNet.Numerics}} |
{{libheader|MathNet.Numerics}} |
||
< |
<syntaxhighlight lang=csharp> |
||
using System; |
using System; |
||
using System.Console; |
using System.Console; |
||
Line 839: | Line 839: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 879: | Line 879: | ||
{{libheader|System.Numerics}} |
{{libheader|System.Numerics}} |
||
Algo based on the example provided in the header of this RC page (the one from Wikipedia). <br/> Extra feature - one can override the default of 60 by supplying a suitable number on the command line. The column widths are not hard-coded, but will adapt to the widths of the items listed. |
Algo based on the example provided in the header of this RC page (the one from Wikipedia). <br/> Extra feature - one can override the default of 60 by supplying a suitable number on the command line. The column widths are not hard-coded, but will adapt to the widths of the items listed. |
||
< |
<syntaxhighlight lang=csharp>using System; |
||
using System.Numerics; |
using System.Numerics; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
Line 937: | Line 937: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Default (nothing entered on command line): |
Default (nothing entered on command line): |
||
Line 1,053: | Line 1,053: | ||
{{Works with|C++11}} |
{{Works with|C++11}} |
||
{{libheader|boost}} |
{{libheader|boost}} |
||
< |
<syntaxhighlight lang=cpp>/** |
||
* Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 |
* Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 |
||
* Apple LLVM version 9.1.0 (clang-902.0.39.1) |
* Apple LLVM version 9.1.0 (clang-902.0.39.1) |
||
Line 1,088: | Line 1,088: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,127: | Line 1,127: | ||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang=clojure> |
||
ns test-project-intellij.core |
ns test-project-intellij.core |
||
Line 1,154: | Line 1,154: | ||
(println q ":" (format-ans ans))) |
(println q ":" (format-ans ans))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,196: | Line 1,196: | ||
Be advised that the pseudocode algorithm specifies (j * (a[j-1] - a[j])) in the inner loop; implementing that as-is gives the wrong value (1/2) where n = 1, whereas subtracting a[j]-a[j-1] yields the correct value (B[1]=-1/2). See [http://oeis.org/A027641 the numerator list]. |
Be advised that the pseudocode algorithm specifies (j * (a[j-1] - a[j])) in the inner loop; implementing that as-is gives the wrong value (1/2) where n = 1, whereas subtracting a[j]-a[j-1] yields the correct value (B[1]=-1/2). See [http://oeis.org/A027641 the numerator list]. |
||
< |
<syntaxhighlight lang=lisp>(defun bernouilli (n) |
||
(loop with a = (make-array (list (1+ n))) |
(loop with a = (make-array (list (1+ n))) |
||
for m from 0 to n do |
for m from 0 to n do |
||
Line 1,238: | Line 1,238: | ||
n |
n |
||
(numerator r) |
(numerator r) |
||
(denominator r)))))</ |
(denominator r)))))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,280: | Line 1,280: | ||
{{Trans|Ruby}} |
{{Trans|Ruby}} |
||
< |
<syntaxhighlight lang=ruby>require "big" |
||
class Bernoulli |
class Bernoulli |
||
Line 1,307: | Line 1,307: | ||
puts "B(%2i) = %*i/%i" % [i, max_width, v.numerator, v.denominator] |
puts "B(%2i) = %*i/%i" % [i, max_width, v.numerator, v.denominator] |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Trans|Python}} |
{{Trans|Python}} |
||
Version 1: compute each number separately. |
Version 1: compute each number separately. |
||
< |
<syntaxhighlight lang=ruby>require "big" |
||
def bernoulli(n) |
def bernoulli(n) |
||
Line 1,325: | Line 1,325: | ||
width = b_nums.map{ |b| b.numerator.to_s.size }.max |
width = b_nums.map{ |b| b.numerator.to_s.size }.max |
||
b_nums.each_with_index { |b,i| puts "B(%2i) = %*i/%i" % [i, width, b.numerator, b.denominator] unless b.zero? } |
b_nums.each_with_index { |b,i| puts "B(%2i) = %*i/%i" % [i, width, b.numerator, b.denominator] unless b.zero? } |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Trans|Python}} |
{{Trans|Python}} |
||
Version 2: create faster generator to compute array of numbers once. |
Version 2: create faster generator to compute array of numbers once. |
||
< |
<syntaxhighlight lang=ruby>require "big" |
||
def bernoulli2(limit) |
def bernoulli2(limit) |
||
Line 1,345: | Line 1,345: | ||
width = b_nums.map{ |b| b.numerator.to_s.size }.max |
width = b_nums.map{ |b| b.numerator.to_s.size }.max |
||
b_nums.each_with_index { |b,i| puts "B(%2i) = %*i/%i" % [i, width, b.numerator, b.denominator] unless b.zero? } |
b_nums.each_with_index { |b,i| puts "B(%2i) = %*i/%i" % [i, width, b.numerator, b.denominator] unless b.zero? } |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,385: | Line 1,385: | ||
This uses the D module from the Arithmetic/Rational task. |
This uses the D module from the Arithmetic/Rational task. |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang=d>import std.stdio, std.range, std.algorithm, std.conv, arithmetic_rational; |
||
auto bernoulli(in uint n) pure nothrow /*@safe*/ { |
auto bernoulli(in uint n) pure nothrow /*@safe*/ { |
||
Line 1,402: | Line 1,402: | ||
foreach (immutable b; berns) |
foreach (immutable b; berns) |
||
writefln("B(%2d) = %*d/%d", b[0], width, b[1].tupleof); |
writefln("B(%2d) = %*d/%d", b[0], width, b[1].tupleof); |
||
}</ |
}</syntaxhighlight> |
||
The output is exactly the same as the Python entry. |
The output is exactly the same as the Python entry. |
||
Line 1,411: | Line 1,411: | ||
Thanks Rudy Velthuis for the [https://github.com/rvelthuis/DelphiBigNumbers Velthuis.BigRationals] library.<br> |
Thanks Rudy Velthuis for the [https://github.com/rvelthuis/DelphiBigNumbers Velthuis.BigRationals] library.<br> |
||
< |
<syntaxhighlight lang=Delphi> |
||
program Bernoulli_numbers; |
program Bernoulli_numbers; |
||
Line 1,443: | Line 1,443: | ||
end; |
end; |
||
readln; |
readln; |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
Line 1,450: | Line 1,450: | ||
Only 'small' rationals are supported in EchoLisp, i.e numerator and demominator < 2^31. So, we create a class of 'large' rationals, supported by the bigint library, and then apply the magic formula. |
Only 'small' rationals are supported in EchoLisp, i.e numerator and demominator < 2^31. So, we create a class of 'large' rationals, supported by the bigint library, and then apply the magic formula. |
||
< |
<syntaxhighlight lang=lisp> |
||
(lib 'bigint) ;; lerge numbers |
(lib 'bigint) ;; lerge numbers |
||
(lib 'gloops) ;; classes |
(lib 'gloops) ;; classes |
||
Line 1,475: | Line 1,475: | ||
(define-method div (Rational Rational) (lambda (r q) |
(define-method div (Rational Rational) (lambda (r q) |
||
(normalize (Rational (* r.a q.b) (* r.b q.a))))) |
(normalize (Rational (* r.a q.b) (* r.b q.a))))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Output}} |
{{Output}} |
||
< |
<syntaxhighlight lang=lisp> |
||
;; Bernoulli numbers |
;; Bernoulli numbers |
||
;; http://rosettacode.org/wiki/Bernoulli_numbers |
;; http://rosettacode.org/wiki/Bernoulli_numbers |
||
Line 1,525: | Line 1,525: | ||
(B 1) → 1 / 2 |
(B 1) → 1 / 2 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang=elixir>defmodule Bernoulli do |
||
defmodule Rational do |
defmodule Rational do |
||
import Kernel, except: [div: 2] |
import Kernel, except: [div: 2] |
||
Line 1,582: | Line 1,582: | ||
end |
end |
||
Bernoulli.task</ |
Bernoulli.task</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,622: | Line 1,622: | ||
=={{header|F sharp|F#}}== |
=={{header|F sharp|F#}}== |
||
{{libheader|MathNet.Numerics.FSharp}} |
{{libheader|MathNet.Numerics.FSharp}} |
||
< |
<syntaxhighlight lang=fsharp> |
||
open MathNet.Numerics |
open MathNet.Numerics |
||
open System |
open System |
||
Line 1,648: | Line 1,648: | ||
printf "" |
printf "" |
||
0 |
0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,687: | Line 1,687: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
One could use the "bernoulli" word from the math.extras vocabulary as follows: |
One could use the "bernoulli" word from the math.extras vocabulary as follows: |
||
<lang>IN: scratchpad |
<syntaxhighlight lang=text>IN: scratchpad |
||
[ |
[ |
||
0 1 1 "%2d : %d / %d\n" printf |
0 1 1 "%2d : %d / %d\n" printf |
||
Line 1,728: | Line 1,728: | ||
58 : 84483613348880041862046775994036021 / 354 |
58 : 84483613348880041862046775994036021 / 354 |
||
60 : -1215233140483755572040304994079820246041491 / 56786730 |
60 : -1215233140483755572040304994079820246041491 / 56786730 |
||
Running time: 0.00489444 seconds</ |
Running time: 0.00489444 seconds</syntaxhighlight> |
||
Alternatively a method described by Brent and Harvey (2011) in "Fast computation of Bernoulli, Tangent and Secant numbers" https://arxiv.org/pdf/1108.0286.pdf is shown. |
Alternatively a method described by Brent and Harvey (2011) in "Fast computation of Bernoulli, Tangent and Secant numbers" https://arxiv.org/pdf/1108.0286.pdf is shown. |
||
<lang>:: bernoulli-numbers ( n -- ) |
<syntaxhighlight lang=text>:: bernoulli-numbers ( n -- ) |
||
n 1 + 0 <array> :> tab |
n 1 + 0 <array> :> tab |
||
1 1 tab set-nth |
1 1 tab set-nth |
||
Line 1,764: | Line 1,764: | ||
"%2d : %d / %d\n" printf |
"%2d : %d / %d\n" printf |
||
] each |
] each |
||
;</ |
;</syntaxhighlight> |
||
It gives the same result as the native implementation, but is slightly faster. |
It gives the same result as the native implementation, but is slightly faster. |
||
<lang>[ 30 bernoulli-numbers ] time |
<syntaxhighlight lang=text>[ 30 bernoulli-numbers ] time |
||
... |
... |
||
Running time: 0.004331652 seconds</ |
Running time: 0.004331652 seconds</syntaxhighlight> |
||
=={{header|Fermat}}== |
=={{header|Fermat}}== |
||
< |
<syntaxhighlight lang=fermat>Func Bern(m) = Sigma<k=0,m>[Sigma<v=0,k>[(-1)^v*Bin(k,v)*(v+1)^m/(k+1)]].; |
||
for i=0, 60 do b:=Bern(i); if b<>0 then !!(i,b) fi od;</ |
for i=0, 60 do b:=Bern(i); if b<>0 then !!(i,b) fi od;</syntaxhighlight> |
||
{{out}}<pre> |
{{out}}<pre> |
||
0 1 |
0 1 |
||
Line 1,809: | Line 1,809: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
{{libheader|GMP}} |
{{libheader|GMP}} |
||
< |
<syntaxhighlight lang=freebasic>' version 08-10-2016 |
||
' compile with: fbc -s console |
' compile with: fbc -s console |
||
' uses gmp |
' uses gmp |
||
Line 1,862: | Line 1,862: | ||
Print :Print "hit any key to end program" |
Print :Print "hit any key to end program" |
||
Sleep |
Sleep |
||
End</ |
End</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>B( 0) = 1/1 |
<pre>B( 0) = 1/1 |
||
Line 1,898: | Line 1,898: | ||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
< |
<syntaxhighlight lang=frink>BernoulliNumber[n] := |
||
{ |
{ |
||
a = new array |
a = new array |
||
Line 1,922: | Line 1,922: | ||
} |
} |
||
println[formatTable[result, "right"]]</ |
println[formatTable[result, "right"]]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,962: | Line 1,962: | ||
=={{header|FunL}}== |
=={{header|FunL}}== |
||
FunL has pre-defined function <code>B</code> in module <code>integers</code>, which is defined as: |
FunL has pre-defined function <code>B</code> in module <code>integers</code>, which is defined as: |
||
< |
<syntaxhighlight lang=funl>import integers.choose |
||
def B( n ) = sum( 1/(k + 1)*sum((if 2|r then 1 else -1)*choose(k, r)*(r^n) | r <- 0..k) | k <- 0..n ) |
def B( n ) = sum( 1/(k + 1)*sum((if 2|r then 1 else -1)*choose(k, r)*(r^n) | r <- 0..k) | k <- 0..n ) |
||
for i <- 0..60 if i == 1 or 2|i |
for i <- 0..60 if i == 1 or 2|i |
||
printf( "B(%2d) = %s\n", i, B(i) )</ |
printf( "B(%2d) = %s\n", i, B(i) )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,015: | Line 2,015: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang=gap>for a in Filtered(List([0 .. 60], n -> [n, Bernoulli(n)]), x -> x[2] <> 0) do |
||
Print(a, "\n"); |
Print(a, "\n"); |
||
od; |
od; |
||
Line 2,050: | Line 2,050: | ||
[ 56, -2479392929313226753685415739663229/870 ] |
[ 56, -2479392929313226753685415739663229/870 ] |
||
[ 58, 84483613348880041862046775994036021/354 ] |
[ 58, 84483613348880041862046775994036021/354 ] |
||
[ 60, -1215233140483755572040304994079820246041491/56786730 ]</ |
[ 60, -1215233140483755572040304994079820246041491/56786730 ]</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang=go>package main |
||
import ( |
import ( |
||
Line 2,079: | Line 2,079: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,121: | Line 2,121: | ||
The implementation of the algorithm is in the function bernoullis. The rest is for printing the results. |
The implementation of the algorithm is in the function bernoullis. The rest is for printing the results. |
||
< |
<syntaxhighlight lang=Haskell>import Data.Ratio |
||
import System.Environment |
import System.Environment |
||
Line 2,143: | Line 2,143: | ||
berno i = 1 % (i + 1) |
berno i = 1 % (i + 1) |
||
ulli _ [_] = [] |
ulli _ [_] = [] |
||
ulli i (x:y:xs) = (i % 1) * (x - y) : ulli (i + 1) (y : xs)</ |
ulli i (x:y:xs) = (i % 1) * (x - y) : ulli (i + 1) (y : xs)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>B(0) = 1/1 |
<pre>B(0) = 1/1 |
||
Line 2,179: | Line 2,179: | ||
====Derivation from Faulhaber's triangle==== |
====Derivation from Faulhaber's triangle==== |
||
< |
<syntaxhighlight lang=haskell>import Data.Bool (bool) |
||
import Data.Ratio (Ratio, denominator, numerator, (%)) |
import Data.Ratio (Ratio, denominator, numerator, (%)) |
||
Line 2,234: | Line 2,234: | ||
rjust :: Int -> a -> [a] -> [a] |
rjust :: Int -> a -> [a] -> [a] |
||
rjust n c = drop . length <*> (replicate n c <>)</ |
rjust n c = drop . length <*> (replicate n c <>)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>Bernouillis from Faulhaber triangle: |
<pre>Bernouillis from Faulhaber triangle: |
||
Line 2,274: | Line 2,274: | ||
The following works in both languages: |
The following works in both languages: |
||
< |
<syntaxhighlight lang=unicon>link "rational" |
||
procedure main(args) |
procedure main(args) |
||
Line 2,293: | Line 2,293: | ||
procedure align(r,n) |
procedure align(r,n) |
||
return repl(" ",n-find("/",r))||r |
return repl(" ",n-find("/",r))||r |
||
end</ |
end</syntaxhighlight> |
||
Sample run: |
Sample run: |
||
Line 2,338: | Line 2,338: | ||
See [[j:Essays/Bernoulli_Numbers|Bernoulli Numbers Essay]] on the J wiki. |
See [[j:Essays/Bernoulli_Numbers|Bernoulli Numbers Essay]] on the J wiki. |
||
< |
<syntaxhighlight lang=j>B=: {.&1 %. (i. ! ])@>:@i.@x:</syntaxhighlight> |
||
'''Task:''' |
'''Task:''' |
||
< |
<syntaxhighlight lang=j> 'B' ,. rplc&'r/_-'"1": (#~ 0 ~: {:"1)(i. ,. B) 61 |
||
B 0 1 |
B 0 1 |
||
B 1 -1/2 |
B 1 -1/2 |
||
Line 2,374: | Line 2,374: | ||
B56 -2479392929313226753685415739663229/870 |
B56 -2479392929313226753685415739663229/870 |
||
B58 84483613348880041862046775994036021/354 |
B58 84483613348880041862046775994036021/354 |
||
B60 -1215233140483755572040304994079820246041491/56786730</ |
B60 -1215233140483755572040304994079820246041491/56786730</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang=java>import org.apache.commons.math3.fraction.BigFraction; |
||
public class BernoulliNumbers { |
public class BernoulliNumbers { |
||
Line 2,398: | Line 2,398: | ||
return A[0]; |
return A[0]; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
<pre>B(0 ) = 1 |
<pre>B(0 ) = 1 |
||
B(1 ) = 1 / 2 |
B(1 ) = 1 / 2 |
||
Line 2,441: | Line 2,441: | ||
'''BigInt Stubs''': |
'''BigInt Stubs''': |
||
< |
<syntaxhighlight lang=jq># def negate: |
||
# def lessOrEqual(x; y): # x <= y |
# def lessOrEqual(x; y): # x <= y |
||
# def long_add(x;y): # x+y |
# def long_add(x;y): # x+y |
||
Line 2,479: | Line 2,479: | ||
def long_mod(x;y): |
def long_mod(x;y): |
||
((x|tonumber) % (y|tonumber)) | tostring;</ |
((x|tonumber) % (y|tonumber)) | tostring;</syntaxhighlight> |
||
'''Fractions''':< |
'''Fractions''':<syntaxhighlight lang=jq> |
||
# A fraction is represented by [numerator, denominator] in reduced form, with the sign on top |
# A fraction is represented by [numerator, denominator] in reduced form, with the sign on top |
||
Line 2,535: | Line 2,535: | ||
| if $a == $b then ["0", "1"] |
| if $a == $b then ["0", "1"] |
||
else add($a; [ ($b[0]|negate), $b[1] ] ) |
else add($a; [ ($b[0]|negate), $b[1] ] ) |
||
end ; </ |
end ; </syntaxhighlight> |
||
'''Bernoulli Numbers''': |
'''Bernoulli Numbers''': |
||
< |
<syntaxhighlight lang=jq># Using the algorithm in the task description: |
||
def bernoulli(n): |
def bernoulli(n): |
||
reduce range(0; n+1) as $m |
reduce range(0; n+1) as $m |
||
Line 2,547: | Line 2,547: | ||
.[$j-1] = multiply( [($j|tostring), "1"]; minus( .[$j-1] ; .[$j]) ) )) |
.[$j-1] = multiply( [($j|tostring), "1"]; minus( .[$j-1] ; .[$j]) ) )) |
||
| .[0] # (which is Bn) |
| .[0] # (which is Bn) |
||
;</ |
;</syntaxhighlight> |
||
'''The task''': |
'''The task''': |
||
< |
<syntaxhighlight lang=jq>range(0;61) |
||
| if . % 2 == 0 or . == 1 then "\(.): \(bernoulli(.) )" else empty end</ |
| if . % 2 == 0 or . == 1 then "\(.): \(bernoulli(.) )" else empty end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
The following output was obtained using the previously mentioned BigInt library. |
The following output was obtained using the previously mentioned BigInt library. |
||
< |
<syntaxhighlight lang=sh>$ jq -n -r -f Bernoulli.jq |
||
0: ["1","1"] |
0: ["1","1"] |
||
1: ["1","2"] |
1: ["1","2"] |
||
Line 2,586: | Line 2,586: | ||
56: ["-2479392929313226753685415739663229","870"] |
56: ["-2479392929313226753685415739663229","870"] |
||
58: ["84483613348880041862046775994036021","354"] |
58: ["84483613348880041862046775994036021","354"] |
||
60: ["-1215233140483755572040304994079820246041491","56786730"]</ |
60: ["-1215233140483755572040304994079820246041491","56786730"]</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang=Julia>function bernoulli(n) |
||
A = Vector{Rational{BigInt}}(undef, n + 1) |
A = Vector{Rational{BigInt}}(undef, n + 1) |
||
for m = 0 : n |
for m = 0 : n |
||
Line 2,634: | Line 2,634: | ||
for (n, b) in enumerate(BernoulliList(60)) |
for (n, b) in enumerate(BernoulliList(60)) |
||
isodd(numerator(b)) && println("B($(n-1)) = $b") |
isodd(numerator(b)) && println("B($(n-1)) = $b") |
||
end </ |
end </syntaxhighlight> |
||
Produces virtually the same output as the Python version. |
Produces virtually the same output as the Python version. |
||
Line 2,642: | Line 2,642: | ||
{{works with|Commons Math|3.3.5}} |
{{works with|Commons Math|3.3.5}} |
||
< |
<syntaxhighlight lang=scala>import org.apache.commons.math3.fraction.BigFraction |
||
object Bernoulli { |
object Bernoulli { |
||
Line 2,663: | Line 2,663: | ||
if (n % 2 == 0 || n == 1) |
if (n % 2 == 0 || n == 1) |
||
System.out.printf("B(%-2d) = %-1s%n", n, Bernoulli(n)) |
System.out.printf("B(%-2d) = %-1s%n", n, Bernoulli(n)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Produces virtually the same output as the Java version. |
Produces virtually the same output as the Java version. |
||
Line 2,672: | Line 2,672: | ||
{{libheader|luagmp}} |
{{libheader|luagmp}} |
||
{{works with|LuaJIT|2.0-2.1}} |
{{works with|LuaJIT|2.0-2.1}} |
||
< |
<syntaxhighlight lang=lua>#!/usr/bin/env luajit |
||
local gmp = require 'gmp' ('libgmp') |
local gmp = require 'gmp' ('libgmp') |
||
local ffi = require'ffi' |
local ffi = require'ffi' |
||
Line 2,716: | Line 2,716: | ||
gmp.z_clears(n,d) |
gmp.z_clears(n,d) |
||
gmp.q_clear(rop) |
gmp.q_clear(rop) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>> time ./bernoulli_gmp.lua |
<pre>> time ./bernoulli_gmp.lua |
||
Line 2,755: | Line 2,755: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang=Maple>print(select(n->n[2]<>0,[seq([n,bernoulli(n,1)],n=0..60)]));</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[[0, 1], [1, 1/2], [2, 1/6], [4, -1/30], [6, 1/42], [8, -1/30], [10, 5/66], [12, -691/2730], [14, 7/6], [16, -3617/510], [18, 43867/798], [20, -174611/330], [22, 854513/138], [24, -236364091/2730], [26, 8553103/6], [28, -23749461029/870], [30, 8615841276005/14322], [32, -7709321041217/510], [34, 2577687858367/6], [36, -26315271553053477373/1919190], [38, 2929993913841559/6], [40, -261082718496449122051/13530], [42, 1520097643918070802691/1806], [44, -27833269579301024235023/690], [46, 596451111593912163277961/282], [48, -5609403368997817686249127547/46410], [50, 495057205241079648212477525/66], [52, -801165718135489957347924991853/1590], [54, 29149963634884862421418123812691/798], [56, -2479392929313226753685415739663229/870], [58, 84483613348880041862046775994036021/354], [60, -1215233140483755572040304994079820246041491/56786730]]</pre> |
<pre>[[0, 1], [1, 1/2], [2, 1/6], [4, -1/30], [6, 1/42], [8, -1/30], [10, 5/66], [12, -691/2730], [14, 7/6], [16, -3617/510], [18, 43867/798], [20, -174611/330], [22, 854513/138], [24, -236364091/2730], [26, 8553103/6], [28, -23749461029/870], [30, 8615841276005/14322], [32, -7709321041217/510], [34, 2577687858367/6], [36, -26315271553053477373/1919190], [38, 2929993913841559/6], [40, -261082718496449122051/13530], [42, 1520097643918070802691/1806], [44, -27833269579301024235023/690], [46, 596451111593912163277961/282], [48, -5609403368997817686249127547/46410], [50, 495057205241079648212477525/66], [52, -801165718135489957347924991853/1590], [54, 29149963634884862421418123812691/798], [56, -2479392929313226753685415739663229/870], [58, 84483613348880041862046775994036021/354], [60, -1215233140483755572040304994079820246041491/56786730]]</pre> |
||
Line 2,761: | Line 2,761: | ||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
Mathematica has no native way for starting an array at index 0. I therefore had to build the array from 1 to n+1 instead of from 0 to n, adjusting the formula accordingly. |
Mathematica has no native way for starting an array at index 0. I therefore had to build the array from 1 to n+1 instead of from 0 to n, adjusting the formula accordingly. |
||
< |
<syntaxhighlight lang=Mathematica>bernoulli[n_] := Module[{a = ConstantArray[0, n + 2]}, |
||
Do[ |
Do[ |
||
a[[m]] = 1/m; |
a[[m]] = 1/m; |
||
Line 2,771: | Line 2,771: | ||
, {m, 1, n + 1}]; |
, {m, 1, n + 1}]; |
||
] |
] |
||
bernoulli[60]</ |
bernoulli[60]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>{0,1} |
<pre>{0,1} |
||
Line 2,809: | Line 2,809: | ||
(Note from task's author: nobody is forced to use any specific algorithm, the one shown is just a suggestion.) |
(Note from task's author: nobody is forced to use any specific algorithm, the one shown is just a suggestion.) |
||
< |
<syntaxhighlight lang=Mathematica>Table[{i, BernoulliB[i]}, {i, 0, 60}]; |
||
Select[%, #[[2]] != 0 &] // TableForm</ |
Select[%, #[[2]] != 0 &] // TableForm</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>0 1 |
<pre>0 1 |
||
Line 2,846: | Line 2,846: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang=Nim>import bignum |
||
import strformat |
import strformat |
||
Line 2,887: | Line 2,887: | ||
for (n, b) in values: |
for (n, b) in values: |
||
let s = fmt"{($b.num).alignString(maxLen, '>')} / {b.denom}" |
let s = fmt"{($b.num).alignString(maxLen, '>')} / {b.denom}" |
||
echo fmt"{n:2}: {s}"</ |
echo fmt"{n:2}: {s}"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,924: | Line 2,924: | ||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang=parigp>for(n=0,60,t=bernfrac(n);if(t,print(n" "t)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>0 1 |
<pre>0 1 |
||
Line 2,962: | Line 2,962: | ||
{{libheader|BigDecimalMath}} |
{{libheader|BigDecimalMath}} |
||
Tested with fpc 3.0.4 |
Tested with fpc 3.0.4 |
||
< |
<syntaxhighlight lang=Pascal> |
||
(* Taken from the 'Ada 99' project, https://marquisdegeek.com/code_ada99 *) |
(* Taken from the 'Ada 99' project, https://marquisdegeek.com/code_ada99 *) |
||
Line 3,085: | Line 3,085: | ||
end; |
end; |
||
end. |
end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 3,129: | Line 3,129: | ||
Instead of doing the same calculations over and over again, I retain the A array until the final Bernoulli number is produced. |
Instead of doing the same calculations over and over again, I retain the A array until the final Bernoulli number is produced. |
||
< |
<syntaxhighlight lang=perl>#!perl |
||
use strict; |
use strict; |
||
use warnings; |
use warnings; |
||
Line 3,153: | Line 3,153: | ||
bernoulli_print(); |
bernoulli_print(); |
||
</syntaxhighlight> |
|||
</lang> |
|||
The output is exactly the same as the Python entry. |
The output is exactly the same as the Python entry. |
||
We can also use modules for faster results. E.g. |
We can also use modules for faster results. E.g. |
||
{{libheader|ntheory}} |
{{libheader|ntheory}} |
||
< |
<syntaxhighlight lang=perl>use ntheory qw/bernfrac/; |
||
for my $n (0 .. 60) { |
for my $n (0 .. 60) { |
||
my($num,$den) = bernfrac($n); |
my($num,$den) = bernfrac($n); |
||
printf "B(%2d) = %44s/%s\n", $n, $num, $den if $num != 0; |
printf "B(%2d) = %44s/%s\n", $n, $num, $den if $num != 0; |
||
}</ |
}</syntaxhighlight> |
||
with identical output. Or: |
with identical output. Or: |
||
< |
<syntaxhighlight lang=perl>use Math::Pari qw/bernfrac/; |
||
for my $n (0 .. 60) { |
for my $n (0 .. 60) { |
||
my($num,$den) = split "/", bernfrac($n); |
my($num,$den) = split "/", bernfrac($n); |
||
printf("B(%2d) = %44s/%s\n", $n, $num, $den||1) if $num != 0; |
printf("B(%2d) = %44s/%s\n", $n, $num, $den||1) if $num != 0; |
||
}</ |
}</syntaxhighlight> |
||
with the difference being that Pari chooses <math>B_1</math> = -½. |
with the difference being that Pari chooses <math>B_1</math> = -½. |
||
Line 3,176: | Line 3,176: | ||
{{libheader|Phix/mpfr}} |
{{libheader|Phix/mpfr}} |
||
{{trans|C}} |
{{trans|C}} |
||
<!--< |
<!--<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: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span> |
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span> |
||
Line 3,208: | Line 3,208: | ||
<span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_free</span><span style="color: #0000FF;">({</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">})</span> |
<span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_free</span><span style="color: #0000FF;">({</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">})</span> |
||
<span style="color: #000000;">rop</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpq_free</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rop</span><span style="color: #0000FF;">)</span> |
<span style="color: #000000;">rop</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpq_free</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rop</span><span style="color: #0000FF;">)</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,247: | Line 3,247: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
Brute force and method by Srinivasa Ramanujan. |
Brute force and method by Srinivasa Ramanujan. |
||
< |
<syntaxhighlight lang=PicoLisp>(load "@lib/frac.l") |
||
(de fact (N) |
(de fact (N) |
||
Line 3,320: | Line 3,320: | ||
(test (berno N) (berno-brute N)) ) |
(test (berno N) (berno-brute N)) ) |
||
(bye)</ |
(bye)</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang=PL/I>Bern: procedure options (main); /* 4 July 2014 */ |
||
declare i fixed binary; |
declare i fixed binary; |
||
declare B complex fixed (31); |
declare B complex fixed (31); |
||
Line 3,355: | Line 3,355: | ||
(3 A, column(10), F(32), 2 A); |
(3 A, column(10), F(32), 2 A); |
||
end; |
end; |
||
end Bern;</ |
end Bern;</syntaxhighlight> |
||
The above uses GCD (see Rosetta Code) extended for 31-digit working. |
The above uses GCD (see Rosetta Code) extended for 31-digit working. |
||
Line 3,384: | Line 3,384: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
===Python: Using task algorithm=== |
===Python: Using task algorithm=== |
||
< |
<syntaxhighlight lang=python>from fractions import Fraction as Fr |
||
def bernoulli(n): |
def bernoulli(n): |
||
Line 3,398: | Line 3,398: | ||
width = max(len(str(b.numerator)) for i,b in bn) |
width = max(len(str(b.numerator)) for i,b in bn) |
||
for i,b in bn: |
for i,b in bn: |
||
print('B(%2i) = %*i/%i' % (i, width, b.numerator, b.denominator))</ |
print('B(%2i) = %*i/%i' % (i, width, b.numerator, b.denominator))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,436: | Line 3,436: | ||
===Python: Optimised task algorithm=== |
===Python: Optimised task algorithm=== |
||
Using the optimization mentioned in the Perl entry to reduce intermediate calculations we create and use the generator bernoulli2(): |
Using the optimization mentioned in the Perl entry to reduce intermediate calculations we create and use the generator bernoulli2(): |
||
< |
<syntaxhighlight lang=python>def bernoulli2(): |
||
A, m = [], 0 |
A, m = [], 0 |
||
while True: |
while True: |
||
Line 3,449: | Line 3,449: | ||
width = max(len(str(b.numerator)) for i,b in bn2) |
width = max(len(str(b.numerator)) for i,b in bn2) |
||
for i,b in bn2: |
for i,b in bn2: |
||
print('B(%2i) = %*i/%i' % (i, width, b.numerator, b.denominator))</ |
print('B(%2i) = %*i/%i' % (i, width, b.numerator, b.denominator))</syntaxhighlight> |
||
Output is exactly the same as before. |
Output is exactly the same as before. |
||
Line 3,455: | Line 3,455: | ||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang=Quackery> $ "bigrat.qky" loadfile |
||
[ 1+ |
[ 1+ |
||
Line 3,479: | Line 3,479: | ||
char / over find |
char / over find |
||
44 swap - times sp |
44 swap - times sp |
||
echo$ cr ] ]</ |
echo$ cr ] ]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,521: | Line 3,521: | ||
{{incorrect|rsplus|This example is incorrect: It is not executable and if made executable (with 'library(gmp)') it returns completely different and wrong results -- not the ones shown here. The R code needs complete rewrite and the 'pracma' library will not be of any help.}} |
{{incorrect|rsplus|This example is incorrect: It is not executable and if made executable (with 'library(gmp)') it returns completely different and wrong results -- not the ones shown here. The R code needs complete rewrite and the 'pracma' library will not be of any help.}} |
||
< |
<syntaxhighlight lang=rsplus> |
||
library(pracma) |
library(pracma) |
||
Line 3,531: | Line 3,531: | ||
cat("B(",idx,") = ",n,"/",d,"\n", sep = "") |
cat("B(",idx,") = ",n,"/",d,"\n", sep = "") |
||
} |
} |
||
</ |
</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,574: | Line 3,574: | ||
use the same emmitter... it's just a matter of how long to wait for the emission. |
use the same emmitter... it's just a matter of how long to wait for the emission. |
||
<lang>#lang racket |
<syntaxhighlight lang=text>#lang racket |
||
;; For: http://rosettacode.org/wiki/Bernoulli_numbers |
;; For: http://rosettacode.org/wiki/Bernoulli_numbers |
||
Line 3,657: | Line 3,657: | ||
(list 1/1 (app abs 1/2) 1/6 -1/30 1/42 -1/30 _ ...)) |
(list 1/1 (app abs 1/2) 1/6 -1/30 1/42 -1/30 _ ...)) |
||
; timing only ... |
; timing only ... |
||
(void (time (bernoulli_0..n bernoulli.3 100))))</ |
(void (time (bernoulli_0..n bernoulli.3 100))))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,700: | Line 3,700: | ||
First, a straighforward implementation of the naïve algorithm in the task description. |
First, a straighforward implementation of the naïve algorithm in the task description. |
||
{{works with|Rakudo|2015.12}} |
{{works with|Rakudo|2015.12}} |
||
<lang |
<syntaxhighlight lang=raku line>sub bernoulli($n) { |
||
my @a; |
my @a; |
||
for 0..$n -> $m { |
for 0..$n -> $m { |
||
Line 3,716: | Line 3,716: | ||
my $form = "B(%2d) = \%{$width}d/%d\n"; |
my $form = "B(%2d) = \%{$width}d/%d\n"; |
||
printf $form, .key, .value.nude for @bpairs;</ |
printf $form, .key, .value.nude for @bpairs;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>B( 0) = 1/1 |
<pre>B( 0) = 1/1 |
||
Line 3,756: | Line 3,756: | ||
{{works with|Rakudo|2015.12}} |
{{works with|Rakudo|2015.12}} |
||
<lang |
<syntaxhighlight lang=raku line>constant bernoulli = gather { |
||
my @a; |
my @a; |
||
for 0..* -> $m { |
for 0..* -> $m { |
||
Line 3,773: | Line 3,773: | ||
my $form = "B(%d)\t= \%{$width}d/%d\n"; |
my $form = "B(%d)\t= \%{$width}d/%d\n"; |
||
printf $form, .key, .value.nude for @bpairs;</ |
printf $form, .key, .value.nude for @bpairs;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>B(0) = 1/1 |
<pre>B(0) = 1/1 |
||
Line 3,833: | Line 3,833: | ||
{{works with|Rakudo|2016.12}} |
{{works with|Rakudo|2016.12}} |
||
<lang |
<syntaxhighlight lang=raku line>sub infix:<bop>(\prev, \this) { |
||
this.key => this.key * (this.value - prev.value) |
this.key => this.key * (this.value - prev.value) |
||
} |
} |
||
Line 3,855: | Line 3,855: | ||
my $form = "B(%d)\t= \%{$width}d/%d\n"; |
my $form = "B(%d)\t= \%{$width}d/%d\n"; |
||
printf $form, .key, .value.nude for @bpairs;</ |
printf $form, .key, .value.nude for @bpairs;</syntaxhighlight> |
||
Same output as memoization example |
Same output as memoization example |
||
Line 3,865: | Line 3,865: | ||
<br> |
<br> |
||
:::::::::::: where <big><big> <math> \binom kr</math> </big></big> is a binomial coefficient. <br> |
:::::::::::: where <big><big> <math> \binom kr</math> </big></big> is a binomial coefficient. <br> |
||
< |
<syntaxhighlight lang=rexx>/*REXX program calculates N number of Bernoulli numbers expressed as vulgar fractions.*/ |
||
parse arg N .; if N=='' | N=="," then N= 60 /*Not specified? Then use the default.*/ |
parse arg N .; if N=='' | N=="," then N= 60 /*Not specified? Then use the default.*/ |
||
numeric digits max(9, n*2) /*increase the decimal digits if needed*/ |
numeric digits max(9, n*2) /*increase the decimal digits if needed*/ |
||
Line 3,919: | Line 3,919: | ||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
perm: procedure expose !.; parse arg x,y; if !.P.x.y\==. then return !.P.x.y |
perm: procedure expose !.; parse arg x,y; if !.P.x.y\==. then return !.P.x.y |
||
z= 1; do j=x-y+1 to x; z= z*j; end; !.P.x.y= z; return z</ |
z= 1; do j=x-y+1 to x; z= z*j; end; !.P.x.y= z; return z</syntaxhighlight> |
||
{{out|output|text= when using the default input:}} |
{{out|output|text= when using the default input:}} |
||
<pre> |
<pre> |
||
Line 3,963: | Line 3,963: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang=ruby>bernoulli = Enumerator.new do |y| |
||
ar = [] |
ar = [] |
||
0.step do |m| |
0.step do |m| |
||
Line 3,976: | Line 3,976: | ||
b_nums.each_with_index {|b,i| puts "B(%2i) = %*i/%i" % [i, width, b.numerator, b.denominator] unless b.zero? } |
b_nums.each_with_index {|b,i| puts "B(%2i) = %*i/%i" % [i, width, b.numerator, b.denominator] unless b.zero? } |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,015: | Line 4,015: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang=rust>// 2.5 implementations presented here: naive, optimized, and an iterator using |
||
// the optimized function. The speeds vary significantly: relative |
// the optimized function. The speeds vary significantly: relative |
||
// speeds of optimized:iterator:naive implementations is 625:25:1. |
// speeds of optimized:iterator:naive implementations is 625:25:1. |
||
Line 4,164: | Line 4,164: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,204: | Line 4,204: | ||
'''With Custom Rational Number Class'''<br/> |
'''With Custom Rational Number Class'''<br/> |
||
(code will run in Scala REPL with a cut-and-paste without need for a third-party library) |
(code will run in Scala REPL with a cut-and-paste without need for a third-party library) |
||
< |
<syntaxhighlight lang=scala>/** Roll our own pared-down BigFraction class just for these Bernoulli Numbers */ |
||
case class BFraction( numerator:BigInt, denominator:BigInt ) { |
case class BFraction( numerator:BigInt, denominator:BigInt ) { |
||
require( denominator != BigInt(0), "Denominator cannot be zero" ) |
require( denominator != BigInt(0), "Denominator cannot be zero" ) |
||
Line 4,253: | Line 4,253: | ||
println( f"$label%-6s $num / ${b.den}" ) |
println( f"$label%-6s $num / ${b.den}" ) |
||
}} |
}} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>b(0) 1 / 1 |
<pre>b(0) 1 / 1 |
||
Line 4,290: | Line 4,290: | ||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
{{works with|Chez Scheme}} |
{{works with|Chez Scheme}} |
||
< |
<syntaxhighlight lang=scheme>; Return the n'th Bernoulli number. |
||
(define bernoulli |
(define bernoulli |
||
Line 4,343: | Line 4,343: | ||
(else |
(else |
||
(printf "B(~2@a) = ~a~%" index (rational-padded (car numbers) max-numerator-length)) |
(printf "B(~2@a) = ~a~%" index (rational-padded (car numbers) max-numerator-length)) |
||
(print-bernoulli (1+ index) (cdr numbers))))))</ |
(print-bernoulli (1+ index) (cdr numbers))))))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>$ scheme --script bernoulli.scm |
<pre>$ scheme --script bernoulli.scm |
||
Line 4,386: | Line 4,386: | ||
function automatically writes repeating decimals in parentheses, when necessary. |
function automatically writes repeating decimals in parentheses, when necessary. |
||
< |
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i"; |
||
include "bigrat.s7i"; |
include "bigrat.s7i"; |
||
Line 4,419: | Line 4,419: | ||
end if; |
end if; |
||
end for; |
end for; |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,459: | Line 4,459: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
Built-in: |
Built-in: |
||
< |
<syntaxhighlight lang=ruby>say bernoulli(42).as_frac #=> 1520097643918070802691/1806</syntaxhighlight> |
||
Recursive solution (with auto-memoization): |
Recursive solution (with auto-memoization): |
||
< |
<syntaxhighlight lang=ruby>func bernoulli_number(n) is cached { |
||
n.is_one && return 1/2 |
n.is_one && return 1/2 |
||
Line 4,475: | Line 4,475: | ||
var Bn = bernoulli_number(n) || next |
var Bn = bernoulli_number(n) || next |
||
printf("B(%2d) = %44s / %s\n", n, Bn.nude) |
printf("B(%2d) = %44s / %s\n", n, Bn.nude) |
||
}</ |
}</syntaxhighlight> |
||
Using Ramanujan's congruences (pretty fast): |
Using Ramanujan's congruences (pretty fast): |
||
< |
<syntaxhighlight lang=ruby>func ramanujan_bernoulli_number(n) is cached { |
||
return 1/2 if n.is_one |
return 1/2 if n.is_one |
||
Line 4,486: | Line 4,486: | ||
binomial(n+3, n - 6*k) * __FUNC__(n - 6*k) |
binomial(n+3, n - 6*k) * __FUNC__(n - 6*k) |
||
})) / binomial(n+3, n) |
})) / binomial(n+3, n) |
||
}</ |
}</syntaxhighlight> |
||
Using Euler's product formula for the Riemann zeta function and the Von Staudt–Clausen theorem (very fast): |
Using Euler's product formula for the Riemann zeta function and the Von Staudt–Clausen theorem (very fast): |
||
< |
<syntaxhighlight lang=ruby>func bernoulli_number_from_zeta(n) { |
||
n.is_zero && return 1 |
n.is_zero && return 1 |
||
Line 4,503: | Line 4,503: | ||
(-1)**(n/2 + 1) * int(ceil(d*K / z)) / d |
(-1)**(n/2 + 1) * int(ceil(d*K / z)) / d |
||
}</ |
}</syntaxhighlight> |
||
The Akiyama–Tanigawa algorithm: |
The Akiyama–Tanigawa algorithm: |
||
< |
<syntaxhighlight lang=ruby>func bernoulli_print { |
||
var a = [] |
var a = [] |
||
for m in (0..60) { |
for m in (0..60) { |
||
Line 4,518: | Line 4,518: | ||
} |
} |
||
bernoulli_print()</ |
bernoulli_print()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,558: | Line 4,558: | ||
=={{header|SPAD}}== |
=={{header|SPAD}}== |
||
{{works with|FriCAS, OpenAxiom, Axiom}} |
{{works with|FriCAS, OpenAxiom, Axiom}} |
||
< |
<syntaxhighlight lang=SPAD> |
||
for n in 0..60 | (b:=bernoulli(n)$INTHEORY; b~=0) repeat print [n,b] |
for n in 0..60 | (b:=bernoulli(n)$INTHEORY; b~=0) repeat print [n,b] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Package:[http://fricas.github.io/api/IntegerNumberTheoryFunctions.html?highlight=bernoulli IntegerNumberTheoryFunctions] |
Package:[http://fricas.github.io/api/IntegerNumberTheoryFunctions.html?highlight=bernoulli IntegerNumberTheoryFunctions] |
||
Line 4,671: | Line 4,671: | ||
Uses the Frac type defined in the [http://rosettacode.org/wiki/Arithmetic/Rational#Swift Rational] task. |
Uses the Frac type defined in the [http://rosettacode.org/wiki/Arithmetic/Rational#Swift Rational] task. |
||
< |
<syntaxhighlight lang=Swift>import BigInt |
||
public func bernoulli<T: BinaryInteger & SignedNumeric>(n: Int) -> Frac<T> { |
public func bernoulli<T: BinaryInteger & SignedNumeric>(n: Int) -> Frac<T> { |
||
Line 4,699: | Line 4,699: | ||
print("B(\(n)) = \(b)") |
print("B(\(n)) = \(b)") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,737: | Line 4,737: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang=tcl>proc bernoulli {n} { |
||
for {set m 0} {$m <= $n} {incr m} { |
for {set m 0} {$m <= $n} {incr m} { |
||
lappend A [list 1 [expr {$m + 1}]] |
lappend A [list 1 [expr {$m + 1}]] |
||
Line 4,762: | Line 4,762: | ||
foreach {n num denom} $result { |
foreach {n num denom} $result { |
||
puts [format {B_%-2d = %*lld/%lld} $n $len $num $denom] |
puts [format {B_%-2d = %*lld/%lld} $n $len $num $denom] |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,802: | Line 4,802: | ||
{{works with|Visual Basic .NET|2013}} |
{{works with|Visual Basic .NET|2013}} |
||
{{libheader|System.Numerics}} |
{{libheader|System.Numerics}} |
||
< |
<syntaxhighlight lang=vbnet>' Bernoulli numbers - vb.net - 06/03/2017 |
||
Imports System.Numerics 'BigInteger |
Imports System.Numerics 'BigInteger |
||
Line 4,851: | Line 4,851: | ||
End Sub 'bernoulli_BigInt |
End Sub 'bernoulli_BigInt |
||
End Module 'Bernoulli_numbers</ |
End Module 'Bernoulli_numbers</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,891: | Line 4,891: | ||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
{{libheader|Wren-big}} |
{{libheader|Wren-big}} |
||
< |
<syntaxhighlight lang=ecmascript>import "/fmt" for Fmt |
||
import "/big" for BigRat |
import "/big" for BigRat |
||
Line 4,911: | Line 4,911: | ||
var b = bernoulli.call(n) |
var b = bernoulli.call(n) |
||
if (b != BigRat.zero) Fmt.print("B($2d) = $44i / $i", n, b.num, b.den) |
if (b != BigRat.zero) Fmt.print("B($2d) = $44i / $i", n, b.num, b.den) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,952: | Line 4,952: | ||
{{trans|EchoLisp}} |
{{trans|EchoLisp}} |
||
Uses lib GMP (GNU MP Bignum Library). |
Uses lib GMP (GNU MP Bignum Library). |
||
< |
<syntaxhighlight lang=zkl>class Rational{ // Weenie Rational class, can handle BigInts |
||
fcn init(_a,_b){ var a=_a, b=_b; normalize(); } |
fcn init(_a,_b){ var a=_a, b=_b; normalize(); } |
||
fcn toString{ "%50d / %d".fmt(a,b) } |
fcn toString{ "%50d / %d".fmt(a,b) } |
||
Line 4,971: | Line 4,971: | ||
} |
} |
||
fcn __opDiv(n){ self(a*n.b,b*n.a) } // Rat / Rat |
fcn __opDiv(n){ self(a*n.b,b*n.a) } // Rat / Rat |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang=zkl>var [const] BN=Import.lib("zklBigNum"); // libGMP (GNU MP Bignum Library) |
||
fcn B(N){ // calculate Bernoulli(n) |
fcn B(N){ // calculate Bernoulli(n) |
||
var A=List.createLong(100,0); // aka static aka not thread safe |
var A=List.createLong(100,0); // aka static aka not thread safe |
||
Line 4,980: | Line 4,980: | ||
} |
} |
||
A[0] |
A[0] |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang=zkl>foreach b in ([0..1].chain([2..60,2])){ println("B(%2d)%s".fmt(b,B(b))) }</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |