fast floor
Spacen Jasset
spacenjasset at yahoo.co.uk
Fri Oct 11 13:31:49 PDT 2013
On 11/10/2013 07:25, monarch_dodra wrote:> 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.
I will have to learn about what "to" does exactly. It wasn't around when
I looked at D x years ago.
My rounding-truncation is for a graphical demo, nothing serious or
accurate, but it's important it be fast. I've found that for my purposes
cast(int) some_float causes the program to run 47% faster, which is what
I was looking for. I am just reading up on the D floating point pages
which I have discovered to see how this works. It is, incidentally a
similar story for C++.
More information about the Digitalmars-d-learn
mailing list