-
-
Save RandyMcMillan/ffc77f0b39fba81f97b0993b6835ccb2 to your computer and use it in GitHub Desktop.
factorial_gamma.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn gamma(n: f64) -> f64 { | |
// For simplicity, we'll use a basic approximation method. | |
// For higher accuracy, consider using a more sophisticated algorithm or a crate | |
// like `special_function` (if it provides Gamma). | |
// We can use integration techniques like the trapezoidal rule or Simpson's rule for approximation. | |
// Here's a basic trapezoidal rule example: | |
let mut result = 0.0; | |
let a = 0.0; | |
let b = 100.0; // Adjust the upper bound as needed for convergence | |
let steps = 1000; // Adjust number of steps for accuracy | |
let h = (b - a) / steps as f64; | |
for i in 0..steps { | |
let x1 = a + i as f64 * h; | |
let x2 = x1 + h; | |
result += (x1.powf(n - 1.0) * (-x1).exp() + x2.powf(n - 1.0) * (-x2).exp()) * h / 2.0; | |
} | |
result | |
} | |
fn factorial(n: u32) -> f64 { | |
if n == 0 { | |
1.0 | |
} else { | |
gamma(n as f64 + 1.0) | |
} | |
} | |
fn main() { | |
for i in 0..10 { | |
println!("{}! = {}", i, factorial(i)); | |
} | |
// Example of calculating factorial of a non-integer using the Gamma function | |
println!("2.5! = {}", factorial(2) + gamma(0.5) ); // Using the property of Gamma function. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment