Re: Blow me away, (long) does not truncate.

From: Nigel Wade (nmw_at_ion.le.ac.uk)
Date: 06/02/04


Date: Wed, 02 Jun 2004 12:57:54 +0100

On Tue, 01 Jun 2004 16:38:56 +0000, Roedy Green wrote:

> On Tue, 01 Jun 2004 09:41:47 +0100, Yu SONG <tips@mi6.gov.uk> wrote or
> quoted :
>
>>The rules are here:
>>http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363
>
> The rules are ambiguous.

No they are not.

> They say they "round toward 0" which could mean ether truncation toward
> 0 or rounding toward 0.

What do you think the difference is between the two?

> In their example they say:
>
> System.out.print("cast to int rounds toward 0: "); d = 12345.6;
> System.out.println((int)d + " " + (int)(-d));
>
>
> produces the output:
>
> cast to int rounds toward 0: 12345 -12345
>
> I ran the test and it indeed truncates.

Of course.

> Which suggests they mean truncation.

They mean either, since either is equally valid.

> Yet the example I ran shows it sometime does rounding.

No, what your example shows is the inaccuracy of floating point numbers.
It has nothing whatever to do with truncation/rounding during conversion
from floating point to integer. The number you entered as
5673892111111112.61 has more significant digits than can be represented in
a double. What is actually stored is the nearest binary representation,
which happens to be 5673892111111113.

What would you expect the result of these calculations to be?

double x1 = 5673892111111112.61;
double x2 = 5673892111111113.0;
double x3 = 5673892111111112.71;
      
double r1 = x2 - x3;
double r2 = x3 - x1;
double r3 = x3 - x2;

> The mystery is explained at http://mindprod.com/jgloss/truncation.html

There is no mystery.

-- 
Nigel Wade, System Administrator, Space Plasma Physics Group,
            University of Leicester, Leicester, LE1 7RH, UK 
E-mail :    nmw@ion.le.ac.uk 
Phone :     +44 (0)116 2523548, Fax : +44 (0)116 2523555