fmod vs. modf vs. floor

This is a discussion on fmod vs. modf vs. floor within the C Programming forums, part of the General Programming Boards category; Probably a trivial question, but what would be the best/fastest way to get the fractional part of a float?
can ...

I would expect modf to be fastest, because it is designed to do specifically what you ask. Judging by the glibc implementation of modf, I'd say this is the case. It does some simple bit manipulations that essentially copies out the fractional part.

I would expect modf to be fastest, because it is designed to do specifically what you ask. Judging by the glibc implementation of modf, I'd say this is the case. It does some simple bit manipulations that essentially copies out the fractional part.

I'll have to look at that one day. Piqued my curiosity in a perverse manner.

Presumably that working is based on the floating value being in some specified range (magnitude less than some threshold). Not all floating point values (eg with a large exponent) will even have a fractional part.

If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

I'll have to look at that one day. Piqued my curiosity in a perverse manner.

Presumably that working is based on the floating value being in some specified range (magnitude less than some threshold). Not all floating point values (eg with a large exponent) will even have a fractional part.

I would expect modf to be fastest, because it is designed to do specifically what you ask. Judging by the glibc implementation of modf, I'd say this is the case. It does some simple bit manipulations that essentially copies out the fractional part.

Do you absolutely have to assign the integral part to another value though? Can I just stick void in there or something? I'm only interested in the fractional part.

I did a quick performance test on Windows (Visual C++) and, of the three methods -- modf, fmod, and floor -- floor ran faster than modf, and both ran much faster than fmod.

Of course I don't have the source code for Windows, but looking at the glibc source for floor, it does "bit twiddling" just like modf. Maybe it's faster because it doesn't pass the extra parameter? I don't know.

One thing that may be an issue with the floor method is floating point round off error. You have to subtract out the floor to get the fractional part. modf just extracts it directly. I'll have to think about this some more...