Best way: float%float

This topic is 4994 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I don't think my way is ideal. Anyone have faster methods. I want (10.1%5.0 == 0.1)
float modulo(float x, float y)
{
while(x > y)
x -= y;

return x;
}


Since 10.1/5.0 == 2.02, if I could remove the 2. then I could get the remainder with .02*5.0.

Share on other sites
something like this should be better.

double   modulo(double lhs, double rhs){//////if (rhs<lhs/2){     lhs=modulo(lhs,rhs*rhs);}while (lhs>rhs){     lhs=lhs-rhs;}return(lhs);}

Share on other sites
Try this:

float floatmod(float x1, float x2) {    return x1 - x2*(int)(x1/x2); }

Share on other sites
#include <math.h>float modulo(float x, float y){    return fmodf(x, y); // having fun?}

Share on other sites
Quote:
 Original post by Beer Hunter *** Source Snippet Removed ***
Yes I thought that they were being quite novel, nicely reinventing the wheel there[smile]
I could do the same and post code for how I am implementing fmod in my hugefloat class, but ... yeah, use fmod from the math header.

Share on other sites
Short answer: Use fmodf from Math.h, like Beer Hunter proposed.

Quote:
 float modulo(float x, float y){ while(x > y) x -= y; return x;}

Does this work with negative numbers?
Also I'd expect to see alot of rounding errors, for instance if the y paramter can't be stored exactly in a float. Then you get a rounding error at every step of the loop.
Quote:
 float floatmod(float x1, float x2) { return x1 - x2*(int)(x1/x2); }

This is more or less the defenition of modulo, and it does work.
However this implementation doesn't really work well with large numbers (i.e x1/x2 > 1 << 31.
One way to handle this is to use ceilf and floorf instead of the (int) cast.

The recursive method I don't want to comment :)
Admintingly a good complier could detect the unnecesary recursion and replace it with a loop, but I still very much doubt that it will be nowhere close in terms of speed to fmodf.

Share on other sites
Just a friendly reminder: In C++, "math.h" is spelled "cmath". :)

• What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 15
• 9
• 11
• 9
• 9
• Forum Statistics

• Total Topics
634131
• Total Posts
3015725
×