fasseg / exp4j

A tiny math expression evaluator for the Java programming language
http://www.objecthunter.net/exp4j/
Apache License 2.0
474 stars 160 forks source link

Complex expressions are not working #122

Open jaydeepbhayani opened 4 months ago

jaydeepbhayani commented 4 months ago

I have an expression like this -> "(0.341 * 8000.0) / (1 - (1 + 0.341) ^ -84)"

Expected result - "109.71908469357446" Actual result - "1.538906384258725e-36"

calculation should be done like below snippet

fun calculateMonthlyInstallment(loanAmount: Double, monthlyInterestRate: Double, numberOfMonths: Int): Double {
    val monthlyInterestRateDecimal = monthlyInterestRate / 100.0  // Convert percentage to decimal
    val power = Math.pow(1 + monthlyInterestRateDecimal, -numberOfMonths.toDouble())
    return (monthlyInterestRateDecimal * loanAmount) / (1 - power)
}

fun main() {
    val loanAmount = 8000.0
    val monthlyInterestRate = 0.341  // 0.5% interest rate
    val numberOfMonths = 84
    val monthlyInstallment = calculateMonthlyInstallment(loanAmount, monthlyInterestRate, numberOfMonths)
    println("Monthly Installment: $monthlyInstallment")
}
RobertZenz commented 4 months ago

Wolfram Alpha says that the result should be 2728?

If I'm not mistaken (which might be, am tired) then your code comes out as:

((0.341 / 100.0) * 8000.0) / (1 - ((1 + (341.0 / 100.0)) ^ -84))

which results in 27.28.

RobertZenz commented 4 months ago

Having said that, both expressions are correctly evaluated by exp4j (0.4.8):

(0.341 * 8000.0) / (1 - (1 + 0.341) ^ -84) = 2728
((0.341 / 100.0) * 8000.0) / (1 - ((1 + (341.0 / 100.0)) ^ -84)) = 27.28
leogtzr commented 4 months ago

I get the exact same result from the "bc" linux utility:

 ~/dev/repos/dev  story-ss-312…enkins-build *2 ?1  bc -lq                                                                                       ✔  2 task  15:44:15 
>>> (0.341 * 8000.0) / (1 - (1 + 0.341) ^ -84)
2728.00000005392957854258
>>> ((0.341 / 100.0) * 8000.0) / (1 - ((1 + (341.0 / 100.0)) ^ -84))
27.28000000000000000000
>>> 

exp4j is evaluating correctly the expression.