Search code examples
javamathlogarithm

Java complex Math.log function giving wrong answer


I am running the following function to simulate power flow.

Math.log( (1000 * d) / ((1000 * d) - p )) / Math.log(1000/999);

I am doing two tests with different values for p

for both:

p = 1333

test 1:

d = 1000000

test 2:

d = 200000

Running through java, both return Infinity

If I put the equation into google, it returns the values I expect. (1386 for test 1, and 162 for test 2)

Equation in google is as

ln( (1000 * (1333)) / ((1000 * (1333)) - (200000) )) / ln(1000/999)

What am I doing wrong?


Solution

  • You are performing Java's integer division with 1000/999, which must result in another int, i.e. 1. The logarithm, any base, of 1 is 0, and dividing by 0 gets you Infinity.

    Use double literals or cast one of the int literals as a double:

    Math.log(1000.0 / 999.0)
    

    or

    Math.log( (double) 1000 / 999)