I saw this post on ruby-talk: raise "false" if ((625.91 + 900.00
+ 22.00) != 1547.91) And yes, of course it raises the exception in ruby or
in C. Guy Decoux (as always) answered quickly:
svg% ruby -e 'p "%.24f" % (625.91 + 900.00 + 22.00)'
"1547.909999999999854480847716"
svg%
svg% ruby -e 'p "%.24f" % 1547.91'
"1547.910000000000081854523160"
svg%
Dave Thomas explained: It’s about 40 years old, and unlikely to be
fixed. Floating point numbers are not represented exactly inside computers,
and so floating point comparisons are routinely deprecated in books on
programming. Certain values cannot ever be expressed in floating point
representation. If you want exact, fractional, math, you should probably
use the ‘rational’ library and investigate ‘mathn’.
This is the classic article to read link What
Every Computer Scientist Should Know About Floating-Point Arithmetic.
Michael Neumann added: In Ruby you can use BigDecimal:
require 'bigdecimal'
BigDecimal.new("625.91") + 900 + 22 == BigDecimal.new("1547.91") # => true
|