这段代码可以很好地计算阶乘,但是用浮点数或十进制数给出错误的答案
fun factorial(number: BigDecimal): BigDecimal {
if (number >= BigDecimal(3000)) {
is_infinity = true
return BigDecimal.ZERO
}
return if (number < BigDecimal.ZERO) {
domain_error = true
BigDecimal.ZERO
} else {
val decimalPartOfNumber = number.toDouble() - number.toInt()
if (decimalPartOfNumber == 0.0) {
var factorial = BigInteger("1")
for (i in 1..number.toInt()) {
factorial *= i.toBigInteger()
}
factorial.toBigDecimal()
} else gammaLanczos(number + BigDecimal.ONE)
}
}
private fun gammaLanczos(x: BigDecimal): BigDecimal {
// https://rosettacode.org/wiki/Gamma_function
var xx = x
val p = doubleArrayOf(
0.9999999999998099,
676.5203681218851,
-1259.1392167224028,
771.3234287776531,
-176.6150291621406,
12.507343278686905,
-0.13857109526572012,
9.984369578019572E-6,
1.5056327351493116e-7
)
val g = BigDecimal(7)
if (xx < BigDecimal(0.5)) return (Math.PI / (sin(Math.PI * xx.toDouble()) * gammaLanczos(BigDecimal(1.0 - xx.toDouble())).toDouble())).toBigDecimal()
xx--
var a = p[0]
val t = xx + g + BigDecimal(0.5)
for (i in 1 until p.size) a += p[i] / (xx.toDouble() + i)
return (sqrt(2.0 * Math.PI) * t.toDouble().pow(xx.toInt() + 0.5) * exp(-t.toDouble()) * a).toBigDecimal()
}
对于下面的代码,测试在运行9个代码后失败,
@Test
fun sqrt() {
val result = NumberFormatter.factorial(BigDecimal(3.03))
assertEquals(6.23120891259, result.toFloat())
}
得到这个预期:6.23120891259但是:5.8062997<><>
有人能帮我吗.谢谢