2021-08-23 00:35:28 +03:00
|
|
|
module math
|
2019-12-27 06:08:17 +03:00
|
|
|
|
|
|
|
// factorial calculates the factorial of the provided value.
|
|
|
|
pub fn factorial(n f64) f64 {
|
2021-08-23 00:35:28 +03:00
|
|
|
// For a large postive argument (n >= factorials_table.len) return max_f64
|
2020-04-09 05:21:11 +03:00
|
|
|
if n >= factorials_table.len {
|
2021-08-23 00:35:28 +03:00
|
|
|
return max_f64
|
2019-12-27 06:08:17 +03:00
|
|
|
}
|
|
|
|
// Otherwise return n!.
|
|
|
|
if n == f64(i64(n)) && n >= 0.0 {
|
2020-04-09 05:21:11 +03:00
|
|
|
return factorials_table[i64(n)]
|
2019-12-27 06:08:17 +03:00
|
|
|
}
|
2021-08-23 00:35:28 +03:00
|
|
|
return gamma(n + 1.0)
|
2019-12-27 06:08:17 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// log_factorial calculates the log-factorial of the provided value.
|
|
|
|
pub fn log_factorial(n f64) f64 {
|
|
|
|
// For a large postive argument (n < 0) return max_f64
|
|
|
|
if n < 0 {
|
2021-08-23 00:35:28 +03:00
|
|
|
return -max_f64
|
2019-12-27 06:08:17 +03:00
|
|
|
}
|
|
|
|
// If n < N then return ln(n!).
|
|
|
|
if n != f64(i64(n)) {
|
2021-08-23 00:35:28 +03:00
|
|
|
return log_gamma(n + 1)
|
2020-04-09 05:21:11 +03:00
|
|
|
} else if n < log_factorials_table.len {
|
2021-05-08 13:32:29 +03:00
|
|
|
return log_factorials_table[i64(n)]
|
|
|
|
}
|
2019-12-27 06:08:17 +03:00
|
|
|
// Otherwise return asymptotic expansion of ln(n!).
|
2021-05-08 13:32:29 +03:00
|
|
|
return log_factorial_asymptotic_expansion(int(n))
|
2019-12-27 06:08:17 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
fn log_factorial_asymptotic_expansion(n int) f64 {
|
2021-05-08 13:32:29 +03:00
|
|
|
m := 6
|
|
|
|
mut term := []f64{}
|
|
|
|
xx := f64((n + 1) * (n + 1))
|
|
|
|
mut xj := f64(n + 1)
|
2021-08-23 00:35:28 +03:00
|
|
|
log_factorial := log_sqrt_2pi - xj + (xj - 0.5) * log(xj)
|
2021-05-08 13:32:29 +03:00
|
|
|
mut i := 0
|
|
|
|
for i = 0; i < m; i++ {
|
2021-08-23 00:35:28 +03:00
|
|
|
term << bernoulli[i] / xj
|
2021-05-08 13:32:29 +03:00
|
|
|
xj *= xx
|
|
|
|
}
|
|
|
|
mut sum := term[m - 1]
|
|
|
|
for i = m - 2; i >= 0; i-- {
|
2021-08-23 00:35:28 +03:00
|
|
|
if abs(sum) <= abs(term[i]) {
|
2021-05-08 13:32:29 +03:00
|
|
|
break
|
|
|
|
}
|
|
|
|
sum = term[i]
|
|
|
|
}
|
|
|
|
for i >= 0 {
|
|
|
|
sum += term[i]
|
|
|
|
i--
|
|
|
|
}
|
|
|
|
return log_factorial + sum
|
2019-12-27 06:08:17 +03:00
|
|
|
}
|