简体   繁体   中英

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?

You are performing Java's integer division with 1000/999 , which must result in another int , ie 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM