float modulo(float x, float y)
{
while(x > y)
x -= y;
return x;
}
Best way: float%float
I don't think my way is ideal. Anyone have faster methods.
I want (10.1%5.0 == 0.1)
Since 10.1/5.0 == 2.02, if I could remove the 2. then I could get the remainder with .02*5.0.
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);}
Quote:Original post by Beer HunterYes I thought that they were being quite novel, nicely reinventing the wheel there[smile]
*** Source Snippet Removed ***
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.
Short answer: Use fmodf from Math.h, like Beer Hunter proposed.
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.
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement