forked from trizen/perl-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinverse_of_factorial_stirling.pl
More file actions
executable file
·48 lines (35 loc) · 1.01 KB
/
inverse_of_factorial_stirling.pl
File metadata and controls
executable file
·48 lines (35 loc) · 1.01 KB
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
40
41
42
43
44
45
46
47
48
#!/usr/bin/perl
# Daniel "Trizen" Șuteu
# License: GPLv3
# Date: 18 September 2016
# Website: https://github.com/trizen
# The inverse of n factorial, based on the inverse of Stirling approximation.
# Formula from:
# https://math.stackexchange.com/questions/430167/is-there-an-inverse-to-stirlings-approximation
use 5.010;
use strict;
use warnings;
use Math::AnyNum qw(:overload tau e factorial);
use constant S => tau->sqrt->log;
use constant T => tau->root(-2.0 * e);
sub inverse_factorial_W {
my ($n) = @_;
my $L = log($n) - S;
$L / ($L / e)->LambertW - 0.5;
}
sub inverse_factorial_lgrt {
my ($n) = @_;
(T * $n**(1 / e))->lgrt * e - 0.5;
}
for my $n (1 .. 100) {
my $f = factorial($n);
my $i = inverse_factorial_W($f);
my $j = inverse_factorial_lgrt($f);
printf("F(%2s!) =~ %s\n", $n, $i);
if ($i->round(-20) != $j->round(-20)) {
die "$i != $j";
}
if ($i->round != $n) {
die "However that is incorrect! (expected: $n -- got ", $i->round, ")";
}
}