3

I think its pretty self explanatory from the code. Obviously I'm no evaluating the same thing over and over, its just example numbers to explain my problem. I'm guessing its over/underflow but I don't know how to deal with it.

double d = (1 / (684985+157781));

System.out.println(d); // returns 0.0
System.out.println(Math.log(d)); // returns -Infinity.
Cheetah
  • 13,785
  • 31
  • 106
  • 190

5 Answers5

8

(1 / (684985+157781)) is an integer expression, so it will come out to 0. The zero then gets assigned to the double d, as 0.0.

Try changing the 1 to 1.0 to force that expression to be a float, or 1.0D to force it to double.

Lesmana
  • 25,663
  • 9
  • 82
  • 87
smendola
  • 2,273
  • 1
  • 15
  • 14
7

Another person done in by integer division:

double d = (1.0 / (684985.0+157781.0));
duffymo
  • 305,152
  • 44
  • 369
  • 561
5

No, in Java if you use integers, the result of division would be again integer, you have to cast least one operand to double.

double d = (1 / (double)(684985+157781));
malejpavouk
  • 4,297
  • 6
  • 41
  • 67
  • I know, but I this approach will work also with variables ;-) – malejpavouk Dec 11 '11 at 21:14
  • yes, it will work, but if you just make the variable a double to begin with. Instead of casting, you can also just use D at the end of the number – D3_JMultiply Dec 11 '11 at 21:18
  • I know :-). But if Ben asked, he probably did not... This example works with variables (and you might have a some good reason to use integers, even though they do not fit in this case). And it also shows more explicitly that something has to be double to enforce the proper implicit conversion. – malejpavouk Dec 11 '11 at 21:32
  • well int/float gives me a float, however If I say `double test = 3F/2;` it gives me 1.5, so floats can be put right into doubles as well... – D3_JMultiply Dec 11 '11 at 22:08
4

Try using double d = (1.0 / (684985+157781));

Note the 1.0 part: you want to force the double evaluation.

Igor Popov
  • 9,795
  • 7
  • 55
  • 68
3

That first expression is computed in integer arithmetic. To get the answer you're expecting, you need to compute it in floating-point arithmetic, thus:

double d = (1.0 / (684985.0+157781.0));
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680