From: Stefan Rusterholz Date: 2007-09-04T11:02:28+09:00 Subject: Re: wierd floating point output William James wrote: > On Sep 3, 5:32 pm, Stefan Rusterholz wrote: >> >> using delta comparison anyway too. >> end >> >> (0.01 + 0.05).in_delta?(0.06) # => true >> 0.01 + 0.05 =~ 0.06 # => true # can't set the delta, is similarly evil >> as == > > class Numeric > def in_delta?(other, delta=Float::EPSILON*16) # chose the delta > wisely > (self-other).abs < delta > end > alias =~ in_delta? > end > > p 1.23456789e4.in_delta?( 1.234567892e4 ) > p 1.23456789e-1.in_delta?( 1.234567892e-1 ) > p 1.23456789e-6.in_delta?( 1.234567892e-6 ) > p 1.23456789e-11.in_delta?( 1.234567892e-11 ) > > ==== output ==== > false > false > true > true That's why, chose your delta wisely. It is also why the =~ is only marginally less surprising than == and still evil. Maybe one could improve it a bit using a delta created using the magnitude (hello, dear log). Another approach might be to use the quotient of the two numbers (its proximity to 1). With both suggestions I have no idea about hazardeous situations, maybe somebody with either more recent CS training or daily use of floats can shed some light on that. Also it is too late at night to have clear thoughts about that. Regards Stefan -- Posted via http://www.ruby-forum.com/.