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

Eduardo Kienetz eduardok at gmail.com
Fri Sep 1 18:19:29 CDT 2006


On 9/1/06, Bernardo Escalona-Espinosa <escalonab at gmail.com> wrote:
> Hello List!
>
> I am really desperate. I need to finish this by monday so I hope some
> of you are home to see this.
>
> I have the following loop:
>
> ===================
>     double step = 0.05;
>     double stop = 4.0;
>
>     int numerator = 4;
>     int denominator = 4;
>
>     int x = 0;
>     int y = 0;
>     int z = 0;
>
>     double beat;
>     double tmp;
>
>     for(beat=0.0; beat<=stop; beat+=step){
>
>       x = int(int(beat)/numerator) + 1;
>       y = int(beat)%numerator + 1;
>       tmp = 10*(beat - int(beat))/2.50 + 1.0;
>       z = int(tmp);
>
>       cout << beat << "\t" << x << "." << y << "." << z << "\t" << tmp << endl;
>     }
> ===================
>
> Maybe it looks like too much for a friday evening but the problem just
> lies in the difference between the variables "tmp" and "z".
>
> Sometimes the operation "int(tmp)" produces unexpected results. 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'm compiling with Dev-C++ on a WinXP SP1 Pentium4.

This is most likely the case:
http://docs.sun.com/source/806-3568/ncg_goldberg.html
http://www.physics.ohio-state.edu/~dws/grouplinks/floating_point_math.pdf

Change your: z = int(tmp); to each of the following (one at a time, of
course), for testing purposes and check the results.

z = int(tmp+0.000000000000001);
z = int(tmp+0.00000000000001);

Just tested it on Linux using g++.

Regards,

-- 
Eduardo  Bacchi Kienetz
LPI Certified - Level 2
http://www.noticiaslinux.com.br/eduardo/



More information about the thelist mailing list