Approximating large factorials:
import math def stirling(n): return math.sqrt(2*math.pi*n) * (n/math.e)**n if __name__ == '__main__': for i in range(1,20): s = stirling(i) f = math.factorial(i) print "stirling: %21.2f factorial: %21d error: %3.2f%%" % (s, f, abs(((f-s)/s)*100.0))
Output:
stirling: 0.92 factorial: 1 error: 8.44%
stirling: 1.92 factorial: 2 error: 4.22%
stirling: 5.84 factorial: 6 error: 2.81%
stirling: 23.51 factorial: 24 error: 2.10%
stirling: 118.02 factorial: 120 error: 1.68%
stirling: 710.08 factorial: 720 error: 1.40%
stirling: 4980.40 factorial: 5040 error: 1.20%
stirling: 39902.40 factorial: 40320 error: 1.05%
stirling: 359536.87 factorial: 362880 error: 0.93%
stirling: 3598695.62 factorial: 3628800 error: 0.84%
stirling: 39615625.05 factorial: 39916800 error: 0.76%
stirling: 475687486.47 factorial: 479001600 error: 0.70%
stirling: 6187239475.19 factorial: 6227020800 error: 0.64%
stirling: 86661001740.60 factorial: 87178291200 error: 0.60%
stirling: 1300430722199.47 factorial: 1307674368000 error: 0.56%
stirling: 20814114415223.14 factorial: 20922789888000 error: 0.52%
stirling: 353948328666101.12 factorial: 355687428096000 error: 0.49%
stirling: 6372804626194313.00 factorial: 6402373705728000 error: 0.46%
stirling: 121112786592294176.00 factorial: 121645100408832000 error: 0.44%
As n increases the error decreases:
n=165 error: 0.0505177446%
n=166 error: 0.0502133452%
n=167 error: 0.0499125922%
n=168 error: 0.0496154204%
n=169 error: 0.0493217663%
No comments:
Post a Comment