aspose file tools*
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 The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript 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
Author

The computation involving multiple types of variables.

cake naiyou
Greenhorn

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
Bartender

Joined: Oct 02, 2003
Posts: 11246
    
  16

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
Bartender

Joined: Sep 20, 2010
Posts: 3615
    
  14

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.
 
 
subject: The computation involving multiple types of variables.