• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

The computation involving multiple types of variables.

 
cake naiyou
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12143
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
did you try it?

I'd write it with and without the cast, print both results, and compare.
 
Stephan van Hulst
Bartender
Pie
Posts: 5889
63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic