Jump to content
  • Advertisement
Sign in to follow this  
Boder

Best way: float%float

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!