I recently wrote a code and haven't been found the bug and start
suspecting that it was
the floating computation that causing the problem. I did a little
experiement and found the
following phenomena:
I am using
Linux source 2.6.15-27-386 #1 PREEMPT Sat Sep 16 01:51:59 UTC 2006 i686
GNU/Linux
Ubuntu is the OS.
···
#####################
#!/usr/bin/ruby1.9
a = 1.0
a.to_f
while(a < 15.0)
a = a + 0.1
print a,"\t",a * a,"\n"
end
#####################
and the output is...(as following) quite odd. Anyone can explain it?
or a way to avoid it (while
keeping the precision)
See this writeup for some details on why this happens.
···
On 11/30/06, teeshift <teeshift@gmail.com> wrote:
I recently wrote a code and haven't been found the bug and start
suspecting that it was
the floating computation that causing the problem. I did a little
experiement and found the
following phenomena:
I am using
Linux source 2.6.15-27-386 #1 PREEMPT Sat Sep 16 01:51:59 UTC 2006 i686
GNU/Linux
Ubuntu is the OS.
Someone else might wish to give a more concrete explanation, but as a
rule, floating-point calculations - using the usual Float datatype -
are not accurate, and prone to rounding errors such as the above.
If you're dealing with limited precision (i.e. X digits after the
decimal point) you should consider using the Decimal datatype instead.
···
On 12/1/06, teeshift <teeshift@gmail.com> wrote:
I recently wrote a code and haven't been found the bug and start
suspecting that it was
the floating computation that causing the problem. I did a little
experiement and found the
following phenomena:
I am using
Linux source 2.6.15-27-386 #1 PREEMPT Sat Sep 16 01:51:59 UTC 2006 i686
GNU/Linux
Ubuntu is the OS.
#####################
#!/usr/bin/ruby1.9
a = 1.0
a.to_f
while(a < 15.0)
a = a + 0.1
print a,"\t",a * a,"\n"
end
#####################
and the output is...(as following) quite odd. Anyone can explain it?
or a way to avoid it (while
keeping the precision)
and the output is...(as following) quite odd. Anyone can explain it?
Floating-point numbers are almost always represented internally in binary
(base 2). For display, they are converted to base ten, but numbers with
fractional parts cannot be displayed perfectly after conversion to base
ten.
For example, the base-ten number 0.1 has no finite representation in base 2
-- it is a continuing, nonterminating fraction, sort of like the decimal
equivalent of 1/3 in base ten.
0.1 in base ten = 0.00011001100110011001101... (forever) in base 2
This is a rite of passage. Everyone goes through this while learning about
computers.