_

johan

On 29-mars-08, at 16:05, Kasper T Toeplitz wrote:

> I was looking for 0.9, so, simple, multiply it by 10. (0.9 * 10. = 9.

> right?)

No.

You should check if abs (x – .9) < something_very_small_like_0.001,

where x is the float you want to compare.

I guess I won’t deserve a beer… anyway mine here are probably tastier

:-)

p

]]>>0.9, but not exactly the same. The number 0.9 can not be represented

>exactly in binary floating point, even if that seems surprising!

>

>So what you’re really doing is multiplying 0.89999989 with ten,

>which works out to 8.9999989, which is *truncated* when converted to

>integer.

ok, of course I remember a lot of mails pointing it

but: how do we know that 0.9 (or the “something very close”) is

closer to/represented as 8.9999989 and not 9.000001 ?????

Are all floats always a little LESS than what is shown???

thanks

kasper

–

Kasper T. Toeplitz

noise, composition, bass, computer

>>

>>Are all floats always a little LESS than what is shown???

>

>No, that’s the reason of the [abs ] object in my proposition.

funny i did not receive your email… cn you re-send it??

k

]]>—————————————————-

> but: how do we know that 0.9 (or the “something very close”) is

> closer to/represented as 8.9999989 and not 9.000001 ?????

—————————————————-

In a binary world, fractions where the denominator is a power of two (like 1/2, 1/4, 1/8, 1/16 etc.) are exact. All other fractions are approximate. We are used to 1/3 being approximated like 0.3333 (mostly). It takes getting used to the idea that 1/10, which works out so nicely with decimal numbers, is not at all nice with binary arithmetic.

In theory it is possible to know exactly how any number will be represented in binary arithmetic, if it will be larger or smaller than the “real” value, but the math is tedious. The way I answer questions like this is to use one of the converters that are available on the web. Or I just assume that however the computer approximates will be exactly the least helpful alternative (a variation on Murphy’s Law).

Both Patrick’s and my suggestions are standard ways of dealing with these problems. Use whichever is most helpful for your needs.

Hope this helps (et merci pour le frommage…)

]]>