[thelist] unexpected c++ casting double to integer behaviour

Lee kowalkowski lee.kowalkowski at googlemail.com
Mon Sep 4 05:12:34 CDT 2006

On 01/09/06, Bernardo Escalona-Espinosa <escalonab at gmail.com> wrote:
> The following iteration from the output shows my problem:
>  2.5     1.3.2     3
> (beat   x.y.z    tmp)
> As you can see, while "tmp" has the value of 3, (or at least, it is
> showing up as 3... i am beginning to think its more like 2.999...) the
> variable "z" is 2. What can I do about this?

I reckon repeatedly incrementing a double variable by 0.05 is not
healthy either.  It's snowballing out of precision.

If you've decided to work to a precision of hundredths, you'd be
better off making that your whole unit.  I.e. long stop = 400; long
beat; for(beat = 0; beat < stop; beat += 5).  Although this means a
simple int would now need to be int(beat / 100) * 100.

Another alternative is do do what graphics programmers do:  Suppose
you're writing a simple rotating cube - If you just repeated this:
rotate it by 1 degree, draw - by the time it had done a one rotation,
it would be noticably distorted.

They avoid this by always transforming from a master, i.e. rotate
master coordinates by 1 degree, draw, rotate master coordinates by 2
degrees, draw...  This cuts down on rounding errors.

You could apply this technique by having an integer control your loop:
for(int i = 0, beat = 0.0; beat <= stop; i++, beat = i * step).


More information about the thelist mailing list