tags:

views:

84

answers:

4
+2  A: 

Read. This is a duplicate of a million other questions.

Stefan Kendall
Post a link to the duplicate instead of posting a non-answer answer.
Sinan Ünür
It's still a legitimate question, this OP is obviously a CS major, first time programmer, who hasn't learned about data types yet.
John Himmelman
@John: It's very much a legitimate question, but it has been answered many, many times already...
Shog9
Shog, many new programmers don't possess the language to communicate (or search for) their problems using technical terms and often post their problems in an example-answer format.
John Himmelman
By not posting the identical posting (of which there are many), I'm teaching the poster to use the search feature of the site. Or something like that.
Stefan Kendall
+2  A: 

Floating point arithmetic in computers is an approximation of the value.

see http://en.wikipedia.org/wiki/Floating_point#Problems_with_floating-point

Jonathan S.
I disagree - it's no more a problem with floating point than 1/3 or π are for the decimal number system. You simply can't represent 0.1 exactly in binary.
duffymo
@duffmo Floating point variables have a given number of bits to encode a numeric value. There are uncountably infinitely many numbers yet only a finite number of bits. Therefore, there will always be some values that cannot be represented whether you use binary or BCD or whatever using the finite number of bits available to you. Now, if you go the arbitrary precision route, you are still limited by the machine's memory which is finite. Now, keep in mind that `1/3` is the most accurate representation of `1/3`.
Sinan Ünür
No, I understand it quite well, thanks. I know all about floating point numbers.
duffymo
@duffymo Are you saying that 0.1 when represented as a float is an approximation of the value 0.1? Sure sounds like you agree with Jonathan if you ignore the "I disagree" part of your comment.
lillq
What duffymo is trying to say is that every number system, regardless of base, will have trouble representing some values using a finite number of digits.This becomes a problem with floating-point because of the *finite* number of bits available for storage according to the spec, as others have pointed out.
Peter
I'm saying that if you try to write the value 0.1 in binary that you won't be able to do it exactly: "Some numbers (e.g., 1/3 and 0.1) cannot be represented exactly in binary floating-point no matter what the precision."
duffymo
There's no such thing as an exact decimal representation of 1/3, regardless. They're called irrational numbers. Same for pi and e.
duffymo
A: 

Math.round() will help you :-)

henchman
A: 

The definitive article to read is

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Sinan Ünür