File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes The computation involving multiple types of variables. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "The computation involving multiple types of variables." Watch "The computation involving multiple types of variables." New topic

The computation involving multiple types of variables.

cake naiyou

Joined: Apr 29, 2011
Posts: 27
For the computations involing diffent types, such as int and double, is the following approach a safe way in tems of no information lost

fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11920

did you try it?

I'd write it with and without the cast, print both results, and compare.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Stephan van Hulst

Joined: Sep 20, 2010
Posts: 4200

As per JLS ยง5.1.2:
Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision

As long as you cast ints to doubles, you may assume the resulting value will be an exact integer representation. However, as soon as you start performing floating point arithmetic on those values, you will lose any such guarantees. So no, the operations you describe are not safe. Whether or not they lose information, they can not guarantee they won't lose information.

It would be wise to treat any operation you perform on floating point values as lossy.

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
I agree. Here's the link:
subject: The computation involving multiple types of variables.
jQuery in Action, 3rd edition