Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int a = (int) ((0.7 + 0.1) * 10). Why a = 7? [duplicate]

Tags:

java

I have question to everybody.

int a = (int) ((0.7 + 0.1) * 10)

After executing of this code, a = 7. I can`t understand why, because (0.7+0.1)=0.8 and 0.8*10=8. Can anybody tell me why? Thanks!

like image 816
Artyom Gilevich Avatar asked Jun 29 '13 19:06

Artyom Gilevich


3 Answers

The issue is that neither 0.1 nor 0.7 can be represented exactly as double:

  • 0.1 gets represented as approximately 0.10000000000000000555.

  • 0.7 gets represented as approximately 0.69999999999999995559.

Their sum is approximately 0.79999999999999993339. Multiplied by ten and truncated, this gives 7.

What Every Computer Scientist Should Know About Floating-Point Arithmetic is an excellent read on the subject.

like image 183
NPE Avatar answered Oct 28 '22 19:10

NPE


It's float arithmetic, it gets floored.

What's happening here is that (0.1+0.7) is really close to 0.8 but it's not actually 0.8, when you multiply it by 10 you get 7.9999... , when you floor that, you get 7.

like image 44
Benjamin Gruenbaum Avatar answered Oct 28 '22 18:10

Benjamin Gruenbaum


The decimal portion of ints in Java is truncated. You can either make x and y floating point variables or just cast them to float and cast them back to get an int as the final result.

like image 38
0x6C38 Avatar answered Oct 28 '22 18:10

0x6C38