[ACCEPTED]-floor()/int() function implementaton-implementation

Accepted answer
Score: 25

Seems to me like

floor(n) = n - (n % 1)

should do the trick.

0

Score: 6

Using the IEEE 754 binary floating point representation one possible solution is:

float myFloor(float x)
{
  if (x == 0.0)
    return 0;

  union
  {
    float input;   // assumes sizeof(float) == sizeof(int)
    int   output;
  } data;

  data.input = x;

  // get the exponent 23~30 bit    
  int exp = data.output & (255 << 23);
  exp = exp >> 23;

  // get the mantissa 0~22 bit
  int man = data.output & ((1 << 23) - 1);

  int pow = exp - 127;
  int mulFactor = 1;

  int i = abs(pow);
  while (i--)
    mulFactor *= 2;

  unsigned long long denominator = 1 << 23;
  unsigned long long numerator = man + denominator;

  // most significant bit represents the sign of the number
  bool negative = (data.output >> 31) != 0;

  if (pow < 0)
    denominator *= mulFactor;
  else
    numerator *= mulFactor;

  float res = 0.0;
  while (numerator >= denominator) {
    res++;
    numerator -= denominator;
  }

  if (negative) {
    res = -res;
    if (numerator != 0)
      res -= 1;
  }

  return res;
}


int main(int /*argc*/, char **/*argv*/)
{
  cout << myFloor(-1234.01234) << " " << floor(-1234.01234) << endl;

  return 0;
}

0

Score: 4
private static int fastFloor(double x) {
    int xi = (int)x;
    return x < xi ? xi - 1 : xi;
}

This is a method similar to Michal Crzardybons 2 answer but it avoids a conditional branch 1 and still handles negative numbers properly.

Score: 2

If result of type 'int' is enough, then 1 here is a simple alternative:

int ifloor( float x )
{
    if (x >= 0)
    {
        return (int)x;
    }
    else
    {
        int y = (int)x;
        return ((float)y == x) ? y : y - 1;
    }
}
Score: 0
int(x)   = x - x%1
floor(x) = int(x)-(x<0 && x%1!=0)
ceil(x)  = int(x)+(x>0 && x%1!=0)
round(x) = floor(x)+(x>0&&x%1>=0.5)+(x<0&&(1+x%1)%1>=0.5)

note: round(x) is not implemented as floor(x+0.5) as this will fail 4 at x=0.5-2^-54

note: logical operations are assumed to convert 3 to integer values 1 for true and 0 for false


Implementations 2 are done so they match the domains defined 1 in int(x), floor(x), ceil(x) and round(x)

Score: 0

The best answer doesn't work for negative 1 numbers so I've modified it:

floor(n) = n - (n % 1 >= 0 ? n%1: (1 + n % 1))
ceil(n) = -floor(-n)
Score: 0

#include<iostream>

int myfloor(int x) {
    if (x > 0)
        return x;
    else
        return x - 1;
}
int main() {
    double x = -5.9;
    std::cout<<myfloor(x);
    


}

0

More Related questions