Best way: float%float

Started by
5 comments, last by Zahlman 18 years, 11 months ago
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.
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);}      
Try this:

float floatmod(float x1, float x2) {    return x1 - x2*(int)(x1/x2); }
#include <math.h>float modulo(float x, float y){    return fmodf(x, y); // having fun?}
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.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
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.
Just a friendly reminder: In C++, "math.h" is spelled "cmath". :)

This topic is closed to new replies.

Advertisement