階乘 n! 僅定義於非負整數。Gamma 函數 是階乘在複數域的解析延拓:
Γ(z) = ∫₀^∞ t^{z-1} e^{-t} dt,滿足 Γ(n) = (n-1)! (正整數 n)。
SpecialFunctions.Gamma(x),完整、高精度、支持複數。Install-Package MathNet.Numerics
using MathNet.Numerics;
double factorial(double x) {
if (x < 0 && x == (int)x) throw new ArgumentException("負整數無階乘 (Gamma 函數極點)");
return SpecialFunctions.Gamma(x + 1); // Γ(x+1) = x!
}
// 用法
Console.WriteLine(factorial(0.5)); // √π/2 ≈ 0.886
Console.WriteLine(factorial(-0.5)); // √π ≈ 1.772
Console.WriteLine(factorial(5)); // 120
x < 0 && x == (int)x 拋出異常或返回 double.NaN。**引入 MathNet.Numerics 一行調用 Gamma 函數,專業、準確、免維護。**