factorial - How to implement Stirling's formula with BigDecimal and BigInteger in Kotlin? -
i'm trying factorial program. if input number below 250 000 use tail recursive function find factorial of number. if input number exceed value of 250 000 try use stirling's formula (). want able work bigintegers , bigdecimals, whenever try calculate 250 102 nan (not number ... error). can please me?
here code in kotlin:
import java.io.file import java.math.bigdecimal import java.math.biginteger tailrec fun tail_recursion_factorial(n: biginteger, factorialofn: biginteger = biginteger.valueof(2)): biginteger { return when(n){ biginteger.zero -> biginteger.one biginteger.one -> biginteger.one biginteger.valueof(2) -> factorialofn else -> tail_recursion_factorial(n.minus(biginteger.one), n.times(factorialofn)) } } // calculate approximate value of n! // using stirling's approximation: fun stirling_factorial(n: biginteger): bigdecimal { return bigdecimal.valueof(math.sqrt((2*n.todouble()*1.0/3.0)*math.pi))*bigdecimal.valueof(math.pow(n.todouble(),n .todouble()))*bigdecimal.valueof(math.pow(math.e,-1.0*n.todouble())) } fun main(args: array<string>){ print("n == ") var n = readline() try { when { biginteger(n) < biginteger.zero -> println("sorry bro! can't factorial negative number.") biginteger(n) >= biginteger.zero -> { when{ biginteger(n) <= biginteger.valueof(250000) -> { file("factorial.txt").writetext("\"$n! ${tail_recursion_factorial(biginteger(n))}\"") println("check factorial.txt in project directory!") } else -> { println("since number bigger 250 000\nwe're calculating using stirling's formula wich approximation of factorial.\n") file("factorial.txt").writetext("the aproximation of $n! is\n${stirling_factorial (biginteger(n))}") println("check factorial.txt in project directory!") } } } } }catch (e: numberformatexception){ println("sorry bro! can't ...") } }
edit: problem solved
import ch.obermuhlner.math.big.bigdecimalmath import java.io.file import java.math.bigdecimal import java.math.mathcontext
and ....
fun stirling_formula(n: bigdecimal) : bigdecimal { val mathcontext = mathcontext(121) return (bigdecimal.one + bigdecimal.one.divide(bigdecimal.valueof(12).times(n),mathcontext)) .times(bigdecimalmath.sqrt((n.times(bigdecimal.valueof(2.0))).times(bigdecimalmath.pi(mathcontext)), mathcontext)) .times(bigdecimalmath.pow(n,n,mathcontext)) .times(bigdecimalmath.pow(bigdecimalmath.e(mathcontext),-n,mathcontext))
all goes alexander romanov
you need proper library such large computations. take @ kotlin-big-math.
val = math.pow(250102.0, 250102.0) println(a) // >> infinity val b = bigdecimal(a) // exception in thread "main" java.lang.numberformatexception: // infinite or nan
Comments
Post a Comment