Jump to content

Bernoulli numbers: Difference between revisions

Line 832:
</pre>
=={{header|factor}}==
One could use the "bernoulli" word from the math.extras vocabulary. Insteadas a method described by Brent and Harvey (2011) in "Fast computation of Bernoulli, Tangent and Secant numbers" httpsfollows://arxiv.org/pdf/1108.0286.pdf is used.
<lang>
IN: scratchpad
:: bernoulli-numbers ( n -- )
1 :> s![
n 1 + 0 <array> :> tab
0 1 1 "%2d : %d / %d\n" printf
1 :> s!
1 -1 2 "%2d : %d / %d\n" printf
1 1 tab set-nth
30 iota [ 1 + 2 * dup bernoulli [ numerator ] [ denominator ] bi
2 n [a,b] [| k |
k 1 - dup "%2d : %d / %d\n" printf ] each
] eachtime
tab nth *
k tab set-nth
] each
2 n [a,b] [| k |
k n [a,b] [| j |
j tab nth
j k - 2 + *
j 1 - tab nth
j k - * +
j tab set-nth
] each
] each
1 n [a,b] [| k |
k 2 * dup
2 swap ^
dup 1 - *
k tab nth
swap / *
s * k tab set-nth
s -1 * s!
] each
0 1 1 "%2d : %d / %d\n" printf
1 -1 2 "%2d : %d / %d\n" printf
1 n [a,b] [| k |
k 2 * k tab nth
[ numerator ] [ denominator ] bi
"%2d : %d / %d\n" printf
] each
 
IN: scratchpad 30 bernoulli-numbers
0 : 1 / 1
1 : -1 / 2
Line 904 ⟶ 873:
58 : 84483613348880041862046775994036021 / 354
60 : -1215233140483755572040304994079820246041491 / 56786730
Running time: 0.00489444 seconds
</lang>
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 -- )
n 1 + 0 <array> :> tab
1 1 tab set-nth
2 n [a,b] [| k |
k 1 - dup
tab nth *
k tab set-nth
] each
2 n [a,b] [| k |
k n [a,b] [| j |
j tab nth
j k - 2 + *
j 1 - tab nth
j k - * +
j tab set-nth
] each
] each
1 :> s!
1 n [a,b] [| k |
k 2 * dup
2^ swapdup ^1 - *
k tab nth
dupswap 1 -/ *
s * k tab set-nth
s -1 * s!
] each
0 1 1 "%2d : %d / %d\n" printf
1 -1 2 "%2d : %d / %d\n" printf
1 n [a,b] [| k |
k 2 * k tab nth
[ numerator ] [ denominator ] bi
"%2d : %d / %d\n" printf
] each
</lang>
It gives the same result as the native implementation, but is slightly faster.
<lang>
IN: scratchpad[ 30 bernoulli-numbers ] time
...
Running time: 0.004331652 seconds
</lang>
 
Cookies help us deliver our services. By using our services, you agree to our use of cookies.