Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting  RSS feed

 
Asher Basheer
Greenhorn
Posts: 17
Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

OUTPUT is....
1.6666666269302368
1.6666666666666667

why is the value typecast by float and double different like this......
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how much do you know about how floating point numbers are stored?
 
Campbell Ritchie
Marshal
Posts: 55687
162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember that casting has a higher precedence than division. A float has about 7 figures' precision and a double about 15-16 figures.
 
Ernie Mcracken
Ranch Hand
Posts: 33
Mac Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A double gives a slightly more accurate representation of rational and irrational numbers because it has more bits dedicated to its precision than a float does, a double has 52 of its 64 to give precision whereas a float only has 23. The rest of the bits are the exponent and the sign bit. when you do (float) 5/3 the result is cast into a float before being assigned to your double so you lose precision this way. You will always have some degree of error when representing irrational numbers with floats or doubles.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernie Mcracken wrote:You will always have some degree of error when representing irrational numbers with floats or doubles.
The original number can be rational, too, and you can still loose precision.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!