[vtkusers] Re: Float to Int

Russell Hind rh_gmane at mac.com
Wed Jul 19 11:37:39 EDT 2006


David Gobbi wrote:
> The problem with this is that the addition introduces some
> roundoff error.  For example, if j = 5.499999 and you add
> 0.5, you might get 6.0 due to roundoff, instead of
> 5.999999 as you would expect.  The method that Patricia
> gave does not suffer from roundoff error.
> 

Ok.  Didn't realise that.  I guess that sort of accuracy when converting 
floats to ints doesn't matter for (yet!).

> Both of these methods only work on on positive numbers,
> since a float-to-int conversion is a truncation operation
> rather than a floor operation.
> 

Yep I release you would need to handle -ve values differently.

> The way to do exact rounding in C++ is the following:
> 
> double x = value;
> double y = floor(x);
> if (x - y >= 0.5) { y++; }
> int i = y;
> 

Thanks, I'll modify our routine to use this.

Cheers

Russell




More information about the vtkusers mailing list