factorial_approximation_from_incomplete_gamma.sf 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 02 February 2019
  4. # https://github.com/trizen
  5. # A new asymptotic formula for approximating n-factorial.
  6. # See also:
  7. # https://en.wikipedia.org/wiki/Incomplete_gamma_function
  8. const π = Num.pi
  9. const e = Num.e
  10. func incomplete_gamma(s, x) {
  11. if (s == 1) {
  12. return exp(-x)
  13. }
  14. ((s-1) * __FUNC__(s-1, x)) + (x**(s-1) * exp(-x))
  15. }
  16. func incomplete_e (n) {
  17. e * incomplete_gamma(n+1, 1) / gamma(n+1)
  18. }
  19. func incomplete_e_asymptotic (n) {
  20. (-sqrt(1/n)/sqrt(2*π) - (11 * (1/n)**(3/2))/(12*sqrt(2*π))) * exp((1 - log(n))*n)
  21. }
  22. # Identity for gamma(n+1) = n!
  23. func approximate_factorial(n) {
  24. var a = (e - incomplete_e(n))
  25. var b = incomplete_e(n-1)
  26. 1 / (e - (a+b))
  27. }
  28. # Concept only.
  29. func approximate_factorial_asymptotic_1(n) {
  30. var a = (e - incomplete_e_asymptotic(n+1))
  31. var b = incomplete_e_asymptotic(n)
  32. 1 / (e - (a + b))
  33. }
  34. # Useful asymptotic formula for n! (derived from #1).
  35. func approximate_factorial_asymptotic_2(n) {
  36. (12*sqrt(2*π)) / (exp(n) * (n**(-n - 3/2) * (12*n + 11) - (e * (n + 1)**(-n - 5/2) * (12*n + 23))))
  37. }
  38. func stirling_approximation(n) {
  39. sqrt(2*π*n) * (n/e)**n
  40. }
  41. var n = 20
  42. say n!
  43. say approximate_factorial(n)
  44. say approximate_factorial_asymptotic_1(n)
  45. say approximate_factorial_asymptotic_2(n)
  46. say stirling_approximation(n)
  47. __END__
  48. 2432902008176640000
  49. 2432902008176639999.99999999999999999999602206663
  50. 2432161531140992146.88707737628241644390204360443
  51. 2432161531140992146.88707737628241644390561053696
  52. 2422786846761133393.68390753895936154169781399601