Bernoulli numbers: Difference between revisions
m
→{{header|Fōrmulæ}}
(Added AppleScript.) |
|||
(14 intermediate revisions by 6 users not shown) | |||
Line 32:
* Luschny's [http://luschny.de/math/zeta/The-Bernoulli-Manifesto.html The Bernoulli Manifesto] for a discussion on <big> '''B<sub>1</sub> = -½''' versus '''+½'''. </big>
<br><br>
=={{header|Ada}}==
Using a GMP thick binding available at http://www.codeforge.com/article/422541
<
USE GMP.Rationals, GMP.Integers, Ada.Text_IO, Ada.Strings.Fixed, Ada.Strings;
Line 67 ⟶ 66:
END IF;
END LOOP;
END Main;</
{{out}}
<pre>
Line 103 ⟶ 102:
B(60)=-1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|ALGOL 68}}==
{{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.
<
# Show Bernoulli numbers B0 to B60 as rational numbers #
Line 184 ⟶ 182:
OD
END
</syntaxhighlight>
{{out}}
<pre>
Line 220 ⟶ 218:
B(60) -1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|AppleScript}}==
<
set listMathScript to getListMathScript(10) -- Script object providing custom list math routines.
set output to {}
-- Akiyama–Tanigawa algorithm for the "second Bernoulli numbers".
-- List 'a' will contain {numerator, denominator} lists
-- The numerators and denominators will in turn be lists containing integers
set a to {}
repeat with m from 0 to n
Line 236 ⟶ 233:
set a's end to result
repeat with j from m to 1 by -1
-- Retrieve the preceding
set {numerator1, denominator1} to a's item j
tell listMathScript
--
set lcd to its lcm(denominator1, denominator2)
set numerator1 to its multiply(numerator1, its |div|(lcd, denominator1))
set numerator2 to its multiply(numerator2, its |div|(lcd, denominator2))
-- Subtract numerator2 from numerator1 and multiply the result by j.
-- Assign the results to numerator2 and denominator2 for the next iteration.
set numerator2 to its multiply(its subtract(numerator1, numerator2), its intToList(j))
set denominator2 to lcd
end tell
--
set a's item j to {numerator2, denominator2}
end repeat
-- The fraction just stored in a's first slot is Bernoulli(m). Reduce it and append a text representation to the output.
tell listMathScript
set gcd to its hcf(numerator2, denominator2)
Line 266 ⟶ 262:
on getListMathScript(base)
script
on multiply(
set
set
set productLength to
set product to {}
repeat productLength times
Line 275 ⟶ 271:
end repeat
-- Long multiplication algorithm, updating product digits on the fly instead of summing rows at the end.
repeat with lst2Index from
if (lst2Digit is not 0) then
set carry to 0
set productIndex to
repeat with
set product's item productIndex to (
set carry to
end tell
set productIndex to productIndex - 1
end repeat
Line 298 ⟶ 296:
end multiply
on subtract(
set
set
copy
repeat (
set
end repeat
repeat (lst1Length - lst2Length)
set lst2's beginning to 0
end repeat
repeat with i from
set
set
if ((lst2Greater) or (lst1Digit > lst2Digit)) then exit repeat
end repeat
-- If so, set up to subtract lst1 from lst2 instead. We'll invert the result's sign at the end.
if (lst2Greater) then tell lst2
set lst2 to lst1
set lst1 to it
end tell
repeat with i from
set difference's beginning to (it mod base)
set borrow to 1 - (it div base)
end tell
end repeat
if (
return difference
end subtract
on |div|(
return divide(
end |div|
on |mod|(
return divide(
end |mod|
on divide(
set dividend to trim(
set divisor to trim(
set dividendLength to (count dividend)
set divisorLength to (count divisor)
if (divisorLength > dividendLength) then return {quotient:{0}, remainder:
-- Note the dividend's and divisor's signs, but use absolute values in the division.
set dividendNegative to (dividend's beginning < 0)
if (dividendNegative) then invert(dividend)
Line 350 ⟶ 356:
if (divisorNegative) then invert(divisor)
-- Long-division algorithm, but quotient digits are subtraction counts.
set quotient to {}
if (divisorLength
set
else
set
end if
repeat with nextSlot from divisorLength to dividendLength
set remainder's end
end repeat
set end of quotient to
end repeat
-- The quotient's negative if the input signs are different.
if (dividendNegative ≠ divisorNegative) then invert(quotient)
-- The remainder
if (dividendNegative) then invert(
return {quotient:quotient, remainder:
end divide
on lcm(
return multiply(
end lcm
on hcf(
set
set
repeat until (
set x to
set
set
end repeat
if (
return
end hcf
Line 398 ⟶ 403:
end invert
on trim(lst) -- Return a copy of
repeat with i from 1 to (count lst)
if (lst's item i is not 0) then exit repeat
Line 444 ⟶ 449:
set output to {""}
set padding to " = "
set bernoulliNumbers to bernoullis(maxN)
repeat with n from 0 to maxN
set bernie to bernoulliNumbers's item (n + 1)
Line 458 ⟶ 463:
end task
task()</
{{output}}
<
B(0) = 1 / 1
B(1) = 1 / 2
Line 493 ⟶ 498:
B(56) = -2479392929313226753685415739663229 / 870
B(58) = 84483613348880041862046775994036021 / 354
B(60) = -1215233140483755572040304994079820246041491 / 56786730"</
=={{header|Bracmat}}==
<
= B Bs answer indLn indexLen indexPadding
, n numberPadding p solPos solidusPos sp
Line 555 ⟶ 559:
& str$!answer
)
& BernoulliList$60;</
<pre>B(0)= 1/1
B(1)= 1/2
Line 588 ⟶ 592:
B(58)= 84483613348880041862046775994036021/354
B(60)=-1215233140483755572040304994079820246041491/56786730</pre>
=={{header|C}}==
{{libheader|GMP}}
<syntaxhighlight lang="c">
#include <stdlib.h>
#include <gmp.h>
Line 643 ⟶ 646:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 679 ⟶ 682:
B(60) = -1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|C sharp|C#}}==
Line 685 ⟶ 687:
{{libheader|Mpir.NET}}
Translation of the C implementation
<
using Mpir.NET;
using System;
Line 739 ⟶ 741:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 779 ⟶ 781:
{{libheader|MathNet.Numerics}}
<
using System;
using System.Console;
Line 831 ⟶ 833:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 871 ⟶ 873:
{{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.
<
using System.Numerics;
using System.Collections.Generic;
Line 929 ⟶ 931:
}
}
</syntaxhighlight>
{{out}}
Default (nothing entered on command line):
Line 1,041 ⟶ 1,043:
B(126) = 5556330281949274850616324408918951380525567307126747246796782304333594286400508981287241419934529638692081513802696639 / 4357878
</pre>
=={{header|C++}}==
{{Works with|C++11}}
{{libheader|boost}}
<
* 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)
Line 1,080 ⟶ 1,081:
return 0;
}</
{{out}}
<pre>
Line 1,116 ⟶ 1,117:
B(60) = -1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|Clojure}}==
<
ns test-project-intellij.core
Line 1,146:
(println q ":" (format-ans ans)))
</syntaxhighlight>
{{out}}
<pre>
Line 1,182:
60 : -1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|Common Lisp}}==
An implementation of the simple algorithm.
Line 1,188 ⟶ 1,187:
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].
<
(loop with a = (make-array (list (1+ n)))
for m from 0 to n do
Line 1,230 ⟶ 1,229:
n
(numerator r)
(denominator r)))))</
{{out}}
Line 1,267 ⟶ 1,266:
B(60): -1215233140483755572040304994079820246041491/56786730
</pre>
=={{header|Crystal}}==
{{Trans|Ruby}}
<
class Bernoulli
Line 1,299 ⟶ 1,297:
puts "B(%2i) = %*i/%i" % [i, max_width, v.numerator, v.denominator]
end
</syntaxhighlight>
{{Trans|Python}}
Version 1: compute each number separately.
<
def bernoulli(n)
Line 1,317 ⟶ 1,315:
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? }
</syntaxhighlight>
{{Trans|Python}}
Version 2: create faster generator to compute array of numbers once.
<
def bernoulli2(limit)
Line 1,337 ⟶ 1,335:
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? }
</syntaxhighlight>
{{out}}
<pre>
Line 1,373 ⟶ 1,371:
B(60) = -1215233140483755572040304994079820246041491/56786730
</pre>
=={{header|D}}==
This uses the D module from the Arithmetic/Rational task.
{{trans|Python}}
<
auto bernoulli(in uint n) pure nothrow /*@safe*/ {
Line 1,394 ⟶ 1,391:
foreach (immutable b; berns)
writefln("B(%2d) = %*d/%d", b[0], width, b[1].tupleof);
}</
The output is exactly the same as the Python entry.
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
Line 1,403 ⟶ 1,399:
Thanks Rudy Velthuis for the [https://github.com/rvelthuis/DelphiBigNumbers Velthuis.BigRationals] library.<br>
<syntaxhighlight lang="delphi">
program Bernoulli_numbers;
Line 1,435 ⟶ 1,431:
end;
readln;
end.</
=={{header|EchoLisp}}==
Line 1,442 ⟶ 1,437:
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.
<
(lib 'bigint) ;; lerge numbers
(lib 'gloops) ;; classes
Line 1,467 ⟶ 1,462:
(define-method div (Rational Rational) (lambda (r q)
(normalize (Rational (* r.a q.b) (* r.b q.a)))))
</syntaxhighlight>
{{Output}}
<
;; Bernoulli numbers
;; http://rosettacode.org/wiki/Bernoulli_numbers
Line 1,517 ⟶ 1,512:
(B 1) → 1 / 2
</syntaxhighlight>
=={{header|Elixir}}==
<
defmodule Rational do
import Kernel, except: [div: 2]
Line 1,574 ⟶ 1,568:
end
Bernoulli.task</
{{out}}
Line 1,611 ⟶ 1,605:
B(60) = -1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|F sharp|F#}}==
{{libheader|MathNet.Numerics.FSharp}}
<
open MathNet.Numerics
open System
Line 1,640 ⟶ 1,633:
printf ""
0
</syntaxhighlight>
{{out}}
<pre>
Line 1,676 ⟶ 1,669:
B(60) = -1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|Factor}}==
One could use the "bernoulli" word from the math.extras vocabulary as follows:
<syntaxhighlight lang="text">IN: scratchpad
[
0 1 1 "%2d : %d / %d\n" printf
Line 1,720 ⟶ 1,712:
58 : 84483613348880041862046775994036021 / 354
60 : -1215233140483755572040304994079820246041491 / 56786730
Running time: 0.00489444 seconds</
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.
<syntaxhighlight lang="text">:: bernoulli-numbers ( n -- )
n 1 + 0 <array> :> tab
1 1 tab set-nth
Line 1,756 ⟶ 1,748:
"%2d : %d / %d\n" printf
] each
;</
It gives the same result as the native implementation, but is slightly faster.
<syntaxhighlight lang="text">[ 30 bernoulli-numbers ] time
...
Running time: 0.004331652 seconds</
=={{header|Fermat}}==
<
for i=0, 60 do b:=Bern(i); if b<>0 then !!(i,b) fi od;</
{{out}}<pre>
0 1
Line 1,798 ⟶ 1,789:
58 84483613348880041862046775994036021 / 354
60 -1215233140483755572040304994079820246041491 / 56786730</pre>
=={{header|FreeBASIC}}==
{{libheader|GMP}}
<
' compile with: fbc -s console
' uses gmp
Line 1,854 ⟶ 1,844:
Print :Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>B( 0) = 1/1
Line 1,888 ⟶ 1,878:
B(58) = 84483613348880041862046775994036021/354
B(60) = -1215233140483755572040304994079820246041491/56786730</pre>
=={{header|Frink}}==
<
{
a = new array
Line 1,914 ⟶ 1,903:
}
println[formatTable[result, "right"]]</
{{out}}
Line 1,951 ⟶ 1,940:
60 -1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|FunL}}==
FunL has pre-defined function <code>B</code> in module <code>integers</code>, which is defined as:
<
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
printf( "B(%2d) = %s\n", i, B(i) )</
{{out}}
Line 1,996 ⟶ 1,984:
B(60) = -1215233140483755572040304994079820246041491/56786730
</pre>
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Bernoulli_numbers}}
'''Solution.''' The following function reduces to the n-th Bernoulli number. It is a replica of the Akiyama–Tanigawa algorithm.
[[File:Fōrmulæ - Bernoulli numbers 01.png]]
'''Test case.''' Showing the Bernoulli numbers B<sub>0</sub> to B<sub>60</sub>
[[File:Fōrmulæ - Bernoulli numbers 02.png]]
[[File:Fōrmulæ - Bernoulli numbers 03.png]]
=={{header|GAP}}==
<
Print(a, "\n");
od;
Line 2,042 ⟶ 2,035:
[ 56, -2479392929313226753685415739663229/870 ]
[ 58, 84483613348880041862046775994036021/354 ]
[ 60, -1215233140483755572040304994079820246041491/56786730 ]</
=={{header|Go}}==
<
import (
Line 2,071 ⟶ 2,063:
}
}
}</
{{out}}
<pre>
Line 2,107 ⟶ 2,099:
B(60) = -1215233140483755572040304994079820246041491/56786730
</pre>
=={{header|Haskell}}==
====Task algorithm====
Line 2,113 ⟶ 2,104:
The implementation of the algorithm is in the function bernoullis. The rest is for printing the results.
<
import System.Environment
Line 2,135 ⟶ 2,126:
berno i = 1 % (i + 1)
ulli _ [_] = []
ulli i (x:y:xs) = (i % 1) * (x - y) : ulli (i + 1) (y : xs)</
{{Out}}
<pre>B(0) = 1/1
Line 2,171 ⟶ 2,162:
====Derivation from Faulhaber's triangle====
<
import Data.Ratio (Ratio, denominator, numerator, (%))
Line 2,226 ⟶ 2,217:
rjust :: Int -> a -> [a] -> [a]
rjust n c = drop . length <*> (replicate n c <>)</
{{Out}}
<pre>Bernouillis from Faulhaber triangle:
Line 2,262 ⟶ 2,253:
58 -> 84483613348880041862046775994036021 / 354
60 -> -1215233140483755572040304994079820246041491 / 56786730</pre>
=={{header|Icon}} and {{header|Unicon}}==
The following works in both languages:
<
procedure main(args)
Line 2,285 ⟶ 2,275:
procedure align(r,n)
return repl(" ",n-find("/",r))||r
end</
Sample run:
Line 2,324 ⟶ 2,314:
->
</pre>
=={{header|J}}==
Line 2,330 ⟶ 2,319:
See [[j:Essays/Bernoulli_Numbers|Bernoulli Numbers Essay]] on the J wiki.
<
'''Task:'''
<
B 0 1
B 1 -1/2
Line 2,366 ⟶ 2,355:
B56 -2479392929313226753685415739663229/870
B58 84483613348880041862046775994036021/354
B60 -1215233140483755572040304994079820246041491/56786730</
=={{header|Java}}==
<
public class BernoulliNumbers {
Line 2,390 ⟶ 2,378:
return A[0];
}
}</
<pre>B(0 ) = 1
B(1 ) = 1 / 2
Line 2,423 ⟶ 2,411:
B(58) = 84483613348880041862046775994036021 / 354
B(60) = -1215233140483755572040304994079820246041491 / 56786730</pre>
=={{header|jq}}==
{{works with|jq|1.4}}
Line 2,433 ⟶ 2,420:
'''BigInt Stubs''':
<
# def lessOrEqual(x; y): # x <= y
# def long_add(x;y): # x+y
Line 2,471 ⟶ 2,458:
def long_mod(x;y):
((x|tonumber) % (y|tonumber)) | tostring;</
'''Fractions''':<
# A fraction is represented by [numerator, denominator] in reduced form, with the sign on top
Line 2,527 ⟶ 2,514:
| if $a == $b then ["0", "1"]
else add($a; [ ($b[0]|negate), $b[1] ] )
end ; </
'''Bernoulli Numbers''':
<
def bernoulli(n):
reduce range(0; n+1) as $m
Line 2,539 ⟶ 2,526:
.[$j-1] = multiply( [($j|tostring), "1"]; minus( .[$j-1] ; .[$j]) ) ))
| .[0] # (which is Bn)
;</
'''The task''':
<
| if . % 2 == 0 or . == 1 then "\(.): \(bernoulli(.) )" else empty end</
{{out}}
The following output was obtained using the previously mentioned BigInt library.
<
0: ["1","1"]
1: ["1","2"]
Line 2,578 ⟶ 2,565:
56: ["-2479392929313226753685415739663229","870"]
58: ["84483613348880041862046775994036021","354"]
60: ["-1215233140483755572040304994079820246041491","56786730"]</
=={{header|Julia}}==
<
A = Vector{Rational{BigInt}}(undef, n + 1)
for m = 0 : n
Line 2,626 ⟶ 2,612:
for (n, b) in enumerate(BernoulliList(60))
isodd(numerator(b)) && println("B($(n-1)) = $b")
end </
Produces virtually the same output as the Python version.
=={{header|Kotlin}}==
{{trans|Java}}
{{works with|Commons Math|3.3.5}}
<
object Bernoulli {
Line 2,655 ⟶ 2,640:
if (n % 2 == 0 || n == 1)
System.out.printf("B(%-2d) = %-1s%n", n, Bernoulli(n))
}</
{{out}}
Produces virtually the same output as the Java version.
=={{header|Lua}}==
LuaJIT version with FFI and GMP library
Line 2,664 ⟶ 2,648:
{{libheader|luagmp}}
{{works with|LuaJIT|2.0-2.1}}
<
local gmp = require 'gmp' ('libgmp')
local ffi = require'ffi'
Line 2,708 ⟶ 2,692:
gmp.z_clears(n,d)
gmp.q_clear(rop)
end</
{{out}}
<pre>> time ./bernoulli_gmp.lua
Line 2,745 ⟶ 2,729:
./bernoulli_gmp.lua 0,02s user 0,00s system 97% cpu 0,022 total</pre>
Time compare: Python 0.591 sec, C 0.023 sec, Lua 0.022-0.025
=={{header|Maple}}==
<
{{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>
=={{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.
<
Do[
a[[m]] = 1/m;
Line 2,763 ⟶ 2,745:
, {m, 1, n + 1}];
]
bernoulli[60]</
{{out}}
<pre>{0,1}
Line 2,801 ⟶ 2,783:
(Note from task's author: nobody is forced to use any specific algorithm, the one shown is just a suggestion.)
<
Select[%, #[[2]] != 0 &] // TableForm</
{{out}}
<pre>0 1
Line 2,836 ⟶ 2,818:
58 84483613348880041862046775994036021/354
60 -(1215233140483755572040304994079820246041491/56786730)</pre>
=={{header|Maxima}}==
Using built-in function bern
<syntaxhighlight lang="maxima">
block(makelist([sconcat("B","(",i,")","="),bern(i)],i,0,60),
sublist(%%,lambda([x],x[2]#0)),
table_form(%%))
</syntaxhighlight>
{{out}}
<pre>
matrix(
["B(0)=", 1],
["B(1)=", -1/2],
["B(2)=", 1/6],
["B(4)=", -1/30],
["B(6)=", 1/42],
["B(8)=", -1/30],
["B(10)=", 5/66],
["B(12)=", -691/2730],
["B(14)=", 7/6],
["B(16)=", -3617/510],
["B(18)=", 43867/798],
["B(20)=", -174611/330],
["B(22)=", 854513/138],
["B(24)=", -236364091/2730],
["B(26)=", 8553103/6],
["B(28)=", -23749461029/870],
["B(30)=", 8615841276005/14322],
["B(32)=", -7709321041217/510],
["B(34)=", 2577687858367/6],
["B(36)=", -26315271553053477373/1919190],
["B(38)=", 2929993913841559/6],
["B(40)=", -261082718496449122051/13530],
["B(42)=", 1520097643918070802691/1806],
["B(44)=", -27833269579301024235023/690],
["B(46)=", 596451111593912163277961/282],
["B(48)=", -5609403368997817686249127547/46410],
["B(50)=", 495057205241079648212477525/66],
["B(52)=", -801165718135489957347924991853/1590],
["B(54)=", 29149963634884862421418123812691/798],
["B(56)=", -2479392929313226753685415739663229/870],
["B(58)=", 84483613348880041862046775994036021/354],
["B(60)=", -1215233140483755572040304994079820246041491/56786730]
)
</pre>
=={{header|Nim}}==
<
import strformat
Line 2,879 ⟶ 2,906:
for (n, b) in values:
let s = fmt"{($b.num).alignString(maxLen, '>')} / {b.denom}"
echo fmt"{n:2}: {s}"</
{{out}}
Line 2,914 ⟶ 2,941:
58: 84483613348880041862046775994036021 / 354
60: -1215233140483755572040304994079820246041491 / 56786730</pre>
=={{header|PARI/GP}}==
<
{{out}}
<pre>0 1
Line 2,950 ⟶ 2,976:
58 84483613348880041862046775994036021/354
60 -1215233140483755572040304994079820246041491/56786730</pre>
=={{header|Pascal|FreePascal}}==
{{libheader|BigDecimalMath}}
Tested with fpc 3.0.4
<syntaxhighlight lang="pascal">
(* Taken from the 'Ada 99' project, https://marquisdegeek.com/code_ada99 *)
Line 3,077 ⟶ 3,102:
end;
end.
</syntaxhighlight>
{{out}}
Line 3,115 ⟶ 3,140:
B(60) : -1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|Perl}}==
The only thing in the suggested algorithm which depends on N is the number of times through the inner block. This means that all but the last iteration through the loop produce the exact same values of A.
Line 3,121 ⟶ 3,145:
Instead of doing the same calculations over and over again, I retain the A array until the final Bernoulli number is produced.
<
use strict;
use warnings;
Line 3,145 ⟶ 3,169:
bernoulli_print();
</syntaxhighlight>
The output is exactly the same as the Python entry.
We can also use modules for faster results. E.g.
{{libheader|ntheory}}
<
for my $n (0 .. 60) {
my($num,$den) = bernfrac($n);
printf "B(%2d) = %44s/%s\n", $n, $num, $den if $num != 0;
}</
with identical output. Or:
<
for my $n (0 .. 60) {
my($num,$den) = split "/", bernfrac($n);
printf("B(%2d) = %44s/%s\n", $n, $num, $den||1) if $num != 0;
}</
with the difference being that Pari chooses <math>B_1</math> = -½.
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
{{trans|C}}
<!--<
<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>
Line 3,200 ⟶ 3,223:
<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>
<!--</
{{out}}
<pre>
Line 3,236 ⟶ 3,259:
B(60) = -1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|PicoLisp}}==
Brute force and method by Srinivasa Ramanujan.
<
(de fact (N)
Line 3,312 ⟶ 3,334:
(test (berno N) (berno-brute N)) )
(bye)</
=={{header|PL/I}}==
<
declare i fixed binary;
declare B complex fixed (31);
Line 3,347 ⟶ 3,368:
(3 A, column(10), F(32), 2 A);
end;
end Bern;</
The above uses GCD (see Rosetta Code) extended for 31-digit working.
Line 3,373 ⟶ 3,394:
B(36)= -26315271553053477373/1919190
</pre>
=={{header|Python}}==
===Python: Using task algorithm===
<
def bernoulli(n):
Line 3,390 ⟶ 3,410:
width = max(len(str(b.numerator)) for i,b in bn)
for i,b in bn:
print('B(%2i) = %*i/%i' % (i, width, b.numerator, b.denominator))</
{{out}}
Line 3,428 ⟶ 3,448:
===Python: Optimised task algorithm===
Using the optimization mentioned in the Perl entry to reduce intermediate calculations we create and use the generator bernoulli2():
<
A, m = [], 0
while True:
Line 3,441 ⟶ 3,461:
width = max(len(str(b.numerator)) for i,b in bn2)
for i,b in bn2:
print('B(%2i) = %*i/%i' % (i, width, b.numerator, b.denominator))</
Output is exactly the same as before.
=={{header|Quackery}}==
<
[ 1+
Line 3,471 ⟶ 3,490:
char / over find
44 swap - times sp
echo$ cr ] ]</
{{out}}
Line 3,508 ⟶ 3,527:
60 -1215233140483755572040304994079820246041491/56786730
</pre>
=={{header|R}}==
{{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.}}
<
library(pracma)
Line 3,523 ⟶ 3,540:
cat("B(",idx,") = ",n,"/",d,"\n", sep = "")
}
</
{{out}}
<pre>
Line 3,559 ⟶ 3,576:
B(60) = -1215233140483755572040304994079820246041491/56786730
</pre>
=={{header|Racket}}==
Line 3,566 ⟶ 3,582:
use the same emmitter... it's just a matter of how long to wait for the emission.
<syntaxhighlight lang="text">#lang racket
;; For: http://rosettacode.org/wiki/Bernoulli_numbers
Line 3,649 ⟶ 3,665:
(list 1/1 (app abs 1/2) 1/6 -1/30 1/42 -1/30 _ ...))
; timing only ...
(void (time (bernoulli_0..n bernoulli.3 100))))</
{{out}}
Line 3,684 ⟶ 3,700:
B(58) = 84483613348880041862046775994036021/354
B(60) = -1215233140483755572040304994079820246041491/56786730</pre>
=={{header|Raku}}==
(formerly Perl 6)
Line 3,692 ⟶ 3,707:
First, a straighforward implementation of the naïve algorithm in the task description.
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku"
my @a;
for 0..$n -> $m {
Line 3,708 ⟶ 3,723:
my $form = "B(%2d) = \%{$width}d/%d\n";
printf $form, .key, .value.nude for @bpairs;</
{{out}}
<pre>B( 0) = 1/1
Line 3,748 ⟶ 3,763:
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku"
my @a;
for 0..* -> $m {
Line 3,765 ⟶ 3,780:
my $form = "B(%d)\t= \%{$width}d/%d\n";
printf $form, .key, .value.nude for @bpairs;</
{{out}}
<pre>B(0) = 1/1
Line 3,825 ⟶ 3,840:
{{works with|Rakudo|2016.12}}
<syntaxhighlight lang="raku"
this.key => this.key * (this.value - prev.value)
}
Line 3,847 ⟶ 3,862:
my $form = "B(%d)\t= \%{$width}d/%d\n";
printf $form, .key, .value.nude for @bpairs;</
Same output as memoization example
Line 3,857 ⟶ 3,872:
<br>
:::::::::::: where <big><big> <math> \binom kr</math> </big></big> is a binomial coefficient. <br>
<
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*/
Line 3,911 ⟶ 3,926:
/*──────────────────────────────────────────────────────────────────────────────────────*/
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</
{{out|output|text= when using the default input:}}
<pre>
Line 3,952 ⟶ 3,967:
Output notes: This version of REXX can compute and display all values up to '''B<sub>110</sub>''' in sub─second.
<br><br>
=={{header|RPL}}==
Fractions such as a/b are here handled through the complex number data structure <code>(a,b)</code>.
2 local words support the algorithm suggested by the task: <code>FracSub</code> substracts 2 fractions and <code>FracSimp</code> make a fraction irreducible
Unfortunately, floating-point precision prevents from going beyond B22.
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ DUP2 IM * ROT IM ROT RE * -
≫ '<span style="color:blue">FracSub</span>' STO
≪ DUP C→R ABS SWAP ABS DUP2 < ≪ SWAP ≫ IFT
'''WHILE''' DUP '''REPEAT''' SWAP OVER MOD '''END'''
DROP /
≫ '<span style="color:blue">FracSimp</span>' STO
≪
{ } 1 ROT 1 + '''FOR''' m
1 m R→C +
'''IF''' m 2 ≥ '''THEN''' m 2 '''FOR''' j
DUP j 1 - GET OVER j GET <span style="color:blue">FracSub</span>
C→R SWAP j 1 - * SWAP R→C
<span style="color:blue">FracSimp</span> j 1 - SWAP PUT
-1 '''STEP END'''
'''NEXT''' 1 GET DUP RE SWAP 0 '''IFTE'''
≫ '<span style="color:blue">BRNOU</span>' STO
|
''( (a,b) (c,d) -- (e,f) )'' with e/f = a/b - c/d
''( (a,b) -- (c,d) )'' with c/d simplified fraction of a/b
get GCD of a and b
divide (a,b) by GCD
''( n -- (a,b) )'' with a/b = B(n)
For m from 1 to n+1 do
A[m] ← 1/m
for j from m to 2 do
(A[j-1] - A[j])
. * (j-1)
A[j-1] ←
return A[1] as a fraction or zero
|}
5 <span style="color:blue">BRNOU</span>
22 <span style="color:blue">BRNOU</span>
{{out}}
<pre>
2: 0
1: (854513,138)
</pre>
===HP-49+ version===
Latest RPL implementations can natively handle long fractions and generate Bernoulli numbers.
{{works with|HP|49}}
≪ { }
0 ROT '''FOR''' n
'''IF''' n 2 > LASTARG MOD AND NOT '''THEN''' n IBERNOULLI + '''END'''
'''NEXT'''
≫ '<span style="color:blue">TASK</span>' STO
60 <span style="color:blue">TASK</span>
{{out}}
<pre>
1: {1 -1/2 1/6 -1/30 1/42 -1/30 5/66 -691/2730 7/6 -3617/510 43867/798 -174611/330 854513/138 -236364091/2730 8553103/6 -23749461029/870 8615841276005/14322 -7709321041217/510 2577687858367/6 -26315271553053477373/1919190 2929993913841559/6 -261082718496449122051/13530 1520097643918070802691/1806 -27833269579301024235023/690 596451111593912163277961/282 -5609403368997817686249127547/46410 495057205241079648212477525/66 -801165718135489957347924991853/1590 9149963634884862421418123812691/798 -2479392929313226753685415739663229/870 84483613348880041862046775994036021/354 -1215233140483755572040304994079820246041491/56786730}
</pre>
Runs in 3 minutes 40 on a HP-50g, against 1 hour and 30 minutes if calculating Bernoulli numbers with the above function.
=={{header|Ruby}}==
{{trans|Python}}
<
ar = []
0.step do |m|
Line 3,968 ⟶ 4,054:
b_nums.each_with_index {|b,i| puts "B(%2i) = %*i/%i" % [i, width, b.numerator, b.denominator] unless b.zero? }
</syntaxhighlight>
{{out}}
<pre>
Line 4,007 ⟶ 4,093:
=={{header|Rust}}==
<
// the optimized function. The speeds vary significantly: relative
// speeds of optimized:iterator:naive implementations is 625:25:1.
Line 4,156 ⟶ 4,242:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 4,192 ⟶ 4,278:
B(60) = -1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|Scala}}==
'''With Custom Rational Number Class'''<br/>
(code will run in Scala REPL with a cut-and-paste without need for a third-party library)
<
case class BFraction( numerator:BigInt, denominator:BigInt ) {
require( denominator != BigInt(0), "Denominator cannot be zero" )
Line 4,245 ⟶ 4,330:
println( f"$label%-6s $num / ${b.den}" )
}}
</syntaxhighlight>
{{out}}
<pre>b(0) 1 / 1
Line 4,282 ⟶ 4,367:
=={{header|Scheme}}==
{{works with|Chez Scheme}}
<
(define bernoulli
Line 4,335 ⟶ 4,420:
(else
(printf "B(~2@a) = ~a~%" index (rational-padded (car numbers) max-numerator-length))
(print-bernoulli (1+ index) (cdr numbers))))))</
{{out}}
<pre>$ scheme --script bernoulli.scm
Line 4,370 ⟶ 4,455:
B(58) = 84483613348880041862046775994036021/354
B(60) = -1215233140483755572040304994079820246041491/56786730</pre>
=={{header|Seed7}}==
The program below uses [http://seed7.sourceforge.net/manual/types.htm#bigRational bigRational]
Line 4,378 ⟶ 4,462:
function automatically writes repeating decimals in parentheses, when necessary.
<
include "bigrat.s7i";
Line 4,411 ⟶ 4,495:
end if;
end for;
end func;</
{{out}}
Line 4,448 ⟶ 4,532:
B(60) = -1215233140483755572040304994079820246041491 / 56786730 -21399949257225333665810744765191097.3(926741511617238745742183076926598872659158222352299560126106)
</pre>
=={{header|Sidef}}==
Built-in:
<
Recursive solution (with auto-memoization):
<
n.is_one && return 1/2
Line 4,467 ⟶ 4,550:
var Bn = bernoulli_number(n) || next
printf("B(%2d) = %44s / %s\n", n, Bn.nude)
}</
Using Ramanujan's congruences (pretty fast):
<
return 1/2 if n.is_one
Line 4,478 ⟶ 4,561:
binomial(n+3, n - 6*k) * __FUNC__(n - 6*k)
})) / binomial(n+3, n)
}</
Using Euler's product formula for the Riemann zeta function and the Von Staudt–Clausen theorem (very fast):
<
n.is_zero && return 1
Line 4,495 ⟶ 4,578:
(-1)**(n/2 + 1) * int(ceil(d*K / z)) / d
}</
The Akiyama–Tanigawa algorithm:
<
var a = []
for m in (0..60) {
Line 4,510 ⟶ 4,593:
}
bernoulli_print()</
{{out}}
Line 4,547 ⟶ 4,630:
B(60) = -1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|SPAD}}==
{{works with|FriCAS, OpenAxiom, Axiom}}
<syntaxhighlight lang="spad">
for n in 0..60 | (b:=bernoulli(n)$INTHEORY; b~=0) repeat print [n,b]
</syntaxhighlight>
Package:[http://fricas.github.io/api/IntegerNumberTheoryFunctions.html?highlight=bernoulli IntegerNumberTheoryFunctions]
Line 4,656 ⟶ 4,738:
Type: Void
</pre>
=={{header|Swift}}==
Line 4,663 ⟶ 4,744:
Uses the Frac type defined in the [http://rosettacode.org/wiki/Arithmetic/Rational#Swift Rational] task.
<
public func bernoulli<T: BinaryInteger & SignedNumeric>(n: Int) -> Frac<T> {
Line 4,691 ⟶ 4,772:
print("B(\(n)) = \(b)")
}</
{{out}}
Line 4,727 ⟶ 4,808:
B(58) = Frac(84483613348880041862046775994036021 / 354)
B(60) = Frac(-1215233140483755572040304994079820246041491 / 56786730)</pre>
=={{header|Tcl}}==
<
for {set m 0} {$m <= $n} {incr m} {
lappend A [list 1 [expr {$m + 1}]]
Line 4,754 ⟶ 4,834:
foreach {n num denom} $result {
puts [format {B_%-2d = %*lld/%lld} $n $len $num $denom]
}</
{{out}}
<pre>
Line 4,790 ⟶ 4,870:
B_60 = -1215233140483755572040304994079820246041491/56786730
</pre>
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2013}}
{{libheader|System.Numerics}}
<
Imports System.Numerics 'BigInteger
Line 4,843 ⟶ 4,922:
End Sub 'bernoulli_BigInt
End Module 'Bernoulli_numbers</
{{out}}
<pre>
Line 4,879 ⟶ 4,958:
B(60)=-1215233140483755572040304994079820246041491/56786730
</pre>
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-big}}
<
import "./big" for BigRat
var bernoulli = Fn.new { |n|
Line 4,903 ⟶ 4,981:
var b = bernoulli.call(n)
if (b != BigRat.zero) Fmt.print("B($2d) = $44i / $i", n, b.num, b.den)
}</
{{out}}
Line 4,944 ⟶ 5,022:
{{trans|EchoLisp}}
Uses lib GMP (GNU MP Bignum Library).
<
fcn init(_a,_b){ var a=_a, b=_b; normalize(); }
fcn toString{ "%50d / %d".fmt(a,b) }
Line 4,963 ⟶ 5,041:
}
fcn __opDiv(n){ self(a*n.b,b*n.a) } // Rat / Rat
}</
<
fcn B(N){ // calculate Bernoulli(n)
var A=List.createLong(100,0); // aka static aka not thread safe
Line 4,972 ⟶ 5,050:
}
A[0]
}</
<
{{out}}
<pre>
|