-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconstant_e_to_n_decimal_places.sf
39 lines (29 loc) · 1.57 KB
/
constant_e_to_n_decimal_places.sf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/ruby
# Daniel "Trizen" Șuteu
# Date: 14 May 2018
# https://github.com/trizen
# Calculate the value of `e` to a given number of decimal places.
# Bonus: PARI/GP program for verifying the value of `k` returned from `number_of_required_terms(n)`:
# isok(n, k) = (k * (log(k)-1) + log(2*Pi*k)/2) / log(10) < n && ((k+1) * (log(k+1)-1) + log(2*Pi*(k+1))/2) / log(10) > n;
# See also:
# https://oeis.org/A119906
# https://en.wikipedia.org/wiki/E_(mathematical_constant)
define τ = Num.tau
func number_of_required_terms(n) {
var t = n*log(10)
n.bsearch_le { |k|
((k*(log(k)-1) + log(τ*k)/2)) <=> t
}
}
func e_constant(places=100) {
var t = number_of_required_terms(places)
say "\nComputing e to #{places} decimal places, requires #{t} terms..."
sum(0..t, {|k| 1 / k! }).as_dec(places)
}
say e_constant()
say e_constant(500)
__END__
Computing e to 100 decimal places, requires 69 terms...
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427
Computing e to 500 decimal places, requires 253 terms...
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320030599218174135966290435729003342952605956307381323286279434907632338298807531952510190115738341879307021540891499348841675092447614606680822648001684774118537423454424371075390777449920695517027618386062613313845830007520449338265602976067371132007093287091274437470472306969772093101416928368190255151086574637721112523897844250569536967707854499699679468644549059879316368892300987931