fast floor

monarch_dodra monarchdodra at gmail.com
Thu Oct 10 23:25:56 PDT 2013


On Thursday, 10 October 2013 at 22:27:14 UTC, Spacen Jasset wrote:
> Hello,
>
> I am after a fast floor function; In fact a fast truncation and 
> conversion to integer. I see that std.math takes a real, and 
> that std.c.math takes a double.
>
> Is there a quicker function, and what might cast(int)1.5f do?
>
> Regards,
>
> Spacen.

casting to int does't "floor" a floating type. It truncates it
towards 0. eg:
cast(int)-2.5 => 2.

Keep that in mind, and ask yourself which you require (in
particular, do you even care about negatives at all)?

AFAIK, the "point" of floor is to have a double "end to end": if
you use:
double df = cast(int)mydouble;
Then:
a) You'll lose performance by transforming to int, when floor is
smart enough not to.
b) if mydouble doesn't fit in an int, it'll fail (in this case,
floor does nothing, but it doesn't clobber your mydouble either.

So, if you don't need a double at the end, I *think* using
cast(int) is probably faster.

To protecte yourself from overflow/underflow problems, you can
also use "to", eg:
int myInt = to!int(myDouble);

As long as you are in positive space, this is probably what you
want, and probably as fast as it gets.

If you have to take into account negative numbers, things get
more hairy. I'd use either of:
to!int(foor(x)); //As suggested by JRW
or
(x < 0) ? -to!int(-x) : to!int(x)

However, you'd have to bench to *really* know which is fastest.

Honestly, at the end of the day, I'd just use
to!int(foor(x));

THEN I'd profile, and then I'd see if it's worth trying to throw
optimizations at it.


More information about the Digitalmars-d-learn mailing list