[LC++]a bit [OT]: float-dificulty

Chris Vine chris at cvine.freeserve.co.uk
Mon Jul 24 02:19:32 UTC 2006

On Saturday 22 July 2006 15:19, Julien Claassen wrote:
> Hi everyone!
>   I try to increase/decrase a floating-point value by a fixed amount like
> this:
>   if ((its_value + incrase_val) <= its_max)
>   {
>     its_value += increase_va;
>   }
>   else
>    // some error
>   But it doesn't work properly. its_max is set to 1.0 and it increases only
> up to 0.9 and if I set the value to 1.0 it only decreases up to 0.1 not
> 0.0. I know there's floating-point inprecision to take into account. But
> how to avoid this?
>   Anyone any idea? I am grateful for everything...
>   Kindest regards

You have given the answer.  Floating point values cannot be compared in the 
way that, say, integer values can be compared.  In floating point 
representation, 0.2 + 0.3 does not necessarily compare true to 0.5.

If you are incrementing in steps of 0.1 and want to increment up to a value of 
1.0 (that is, stop a loop incrementing to 1.1), then you can compare against 
a value of 1.01 instead of a value of 1.0.


More information about the tuxCPProgramming mailing list