From: Marko Schulz Date: 2002-03-20T23:12:06+09:00 Subject: Re: Float comparison On Wed, Mar 20, 2002 at 06:49:49PM +0900, rubydev.deweerdt wrote: > Hi, > I'd need to compare floats with a choosen precision, a sort of : > > 3.1415 == (2) 3.1416 #The (n) being the precision > Would be true > 3.1415 == (4) 3.1416 > Would be false > > Is there a way in Ruby to accomplish this ? You could redefine Float#eql? class Float def eql?(other, delta = 0) (self - other).abs <= delta end end p 3.1415.eql?(3.1416, 0.001) #-> true p 3.1415.eql?(3.1416, 0.00001) #-> false p 3.1415.eql?(3.1415) #-> true To prevent some errors concerning rounding it may be better to handle the case of delta==0 special: class Float def eql?(other, delta = 0) if delta == 0 self == other else (self - other).abs <= delta end end end Then again I am a little bit afraid of a recursion trap when defining .eql? with ==, since I do not know Rubys internals. -- marko schulz