Power in Java other than Excel

Asked

Viewed 163 times

-2

I’m having a problem to convert an Excel formula to Java/Kotlin. The scenario is as follows, in Excel I have:

Interest rate: 0.07

Excel calculus:

=(1+taxaDeJuros)^12-1 = %125.22

No Kotlin:

val result = Math.pow((1+taxaDeJuros), 12.00 - 1)) = 2.104851952299

If you put in Excel the formula =(1+taxaDeJuros)^(12-1) the result will be the same in Kotlin (2.104851952299), meaning that Kotlin is putting the parentheses in the (12.00-1).

2 answers

5

Kotlin is not "parenting," it’s just executing things in the order you indicated.

What happens is that Math.pow is a method that takes two arguments: the base and the exponent - and they are separated by a comma. So:

Math.pow( base, expoente )

That is, in Math.pow((1+taxaDeJuros), 12.00 - 1), the basis is (1 + taxaDeJuros) (and these parentheses could even be removed) and the exponent is 12.00 - 1. So first he calculates these values, then he calls Math.pow.
I mean, it’s like I called Math.pow(1 + taxaDeJuros, 11.0).

In the case of Excel, the evaluation of the formula (1+taxaDeJuros)^12-1 are using the order of precedence of the operators: first calculate what is inside the parentheses ((1 + taxaDeJuros)), then do the exponentiation (using the exponent 12.0), and finally subtracts 1.

If you want this same result in Kotlin, just put the subtraction out of the exponentiation:

val result = Math.pow(1 + taxaDeJuros, 12.0) - 1

Another option is to use kotlin.math.pow, so it stays a little closer to the Excel formula (and probably so make clearer the order in which each operation is done):

import kotlin.math.pow

val result = (1 + taxaDeJuros).pow(12.0) - 1

So I think it’s clearer that he makes the sum first 1 + taxaDeJuros, then raise to 12, then subtract 1.

Also note that you don’t need two zeroes after the point, it’s redundant. 12.0 is sufficient to indicate that it is a double. And in the second case, the exponent could also be 12:

import kotlin.math.pow

val result = (1 + taxaDeJuros).pow(12) - 1

Check on Ideone.com all the options above running.

-3


Try it like this:

val result = Math.pow((1 + taxaDeJuros), 12.00) - 1
  • 1

    Thank you very much, vlw.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.