[vtk-developers] Fast floor/round in VTK

David Gobbi david.gobbi at gmail.com
Fri Oct 8 10:11:21 EDT 2010


On Fri, Sep 24, 2010 at 1:46 PM, Bill Lorensen <bill.lorensen at gmail.com> wrote:
> We went through this rounding mess in ITK about a year ago.  We have
> two rounding functions:
> RoundHalfIntegerUp with is also called Round
>  Round towards nearest integer
> and
> RoundHalfIntegerToEven
>
> They are implemented in what I thin is a complex way, but it seems to
> work cross platform.
>
> The code is in ITK/Code/Common/itkMath.h
>
> The implementation are in itkMathDetail. It supports various hardware
> accelerations.
>
> Bill

I've looked into the ITK code a bit more, I'll be using a modified
version of it in my own code and will probably push to have it merged
into VTK somewhere down the line.  If I do the merge, the signatures
will probably be like so, to easily support rounding to both 32-bit
and 64-bit integers (and vtkIdType, which can be either/or):

void vtkMath::Round(double x, vtkTypeInt32 &i);
void vtkMath::Round(double x, vtkTypeInt64 &i);

The above will guarantee that no-one accidentally rounds to 32-bit int
when they mean to round to 64-bit int.

For now, though, I've just updated the existing vtkMath::Floor()
function so that it is accelerated in a platform-independent manner,
instead of being accelerated only for i386:

int vtkMath::Floor(double x)
{
  const int r = static_cast<int>(x);
  const int n = ( x != static_cast<double>(r) );
  const int g = ( x < 0 );
  return r - ( n & g );
}

I know that it is obfuscated, but I formulated it specifically to make
sure that there is no branching.  I've looked at the assembly language
produced by gcc for i386, x86_64, and ppc64 and all are very compact.

  David



More information about the vtk-developers mailing list