-1

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?

KilleR
  • 71
  • 1
  • 7

1 Answers1

6

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)
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • The same problem is happening with the numerator if `d` and `p` are declared as `int` variables. One should declare them as `float` or `double`, or, if that's not appropriate, use floating point literals (e.g., `(1000.0 * d) / ((1000.0 * d) - p )`) to force the type conversion before the division takes place. – Ted Hopp Aug 26 '14 at 16:42
  • @TedHopp When I ran this code with `int` `d` and `p`, I got `NaN`, presumably because `int` division was occurring there too. I could only duplicate the OP's `Infinity` if `d` and `p` were already `double`. But, you're right that it's worth noting that integer division could have occurred there too. – rgettman Aug 26 '14 at 16:45
  • Right. NaN would be the result of evaluating 0 / 0. I should have realized that since OP was getting Infinity, the numerator wasn't evaluating to 0; hence at least one of `d` and `p` must be declared as a floating point type. – Ted Hopp Aug 26 '14 at 17:18
  • Precisely the problem, thank you. I'd already set d and p to be doubles because I'd picked up that problem earlier, but forgot that the second Math.log() would be having the same problem. – KilleR Aug 26 '14 at 17:22