From: Stefan Rusterholz Date: 2007-09-04T07:32:21+09:00 Subject: Re: wierd floating point output Matthias W辰chter wrote: > Stefan Rusterholz schrieb: >> Matthias W辰chter wrote: >>> What I mean is that any float stored as a IEEE 754 double (64 bit), >>> like 0.1 with hex notation 0x3FB999999999999A should have a distinct >>> string representation such that (a==b) == (a.to_s==b.to_s). Note >>> that the next higher double 0.1+2.0**-56 with hex notation >>> 0x3FB999999999999B has the same .to_s representation, which is not good. >> I disagree. As long as you're calculating, you are working with floats >> anyway, so you have maximum precision. Comparing floats should be done >> using delta comparison anyway too. > > Which, as discussed in the 0.06 thread, is hard to accomplish > nevertheless. Anyway. Is it? That's news to me. class Numeric def delta?(other, delta=Float::EPSILON*16) # chose the delta wisely (self-other).abs < delta end alias =~ delta? 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 == >> Comparing floats as string is slightly put stupid. > > It was the code meaning of "if two numbers are identical, I want to see > a difference in the string representation, too). Not more. And that's where you don't understand floats obviously. Floats are *approximations*. Never test approximations for identity. That's destined to fail. If you want identity, use an exact system as mentioned often enough by now I think. E.g. Rational, BigDecimal or whatever else floats your boat. > Does noone care about on some platforms, Ruby is not able to correctly > output floating points with the asked precision? Ruby? Are you sure you found the culprit there? Are you sure ruby doesn't just wrap around whatever float libs are available on the platform? Because in that case, it's your platform that is to blame, not ruby. I don't know it, and I won't go into the source to verify it, but I wouldn't just go around and blame ruby without being sure. I understood that floats are approximations, and it doesn't bother me much (maybe it would if I did scientific calculations - but then I'd probably know a bit more about it and/or use different means) whether the approximation is 0.000000000000010% or 0.000000000000006% off (that's the difference in your 0.1 example - notice something?). > what does ruby -e 'print "%.60f" %0.1' output on your platform? Why would it matter? > Again, it's not a matter of taste how a floating point value is > transferred back to decimals. This can be done unambiguously, especially > if enough positions after decimal point are requested like in "print > %.60f". It's just rather pointless as at some time in your calculation, you lost precision already. So now let me ask you, what do you do that you need 60 places? Are you sure floats are the right tool? Regards Stefan -- Posted via http://www.ruby-forum.com/.