Floor () / int () implementation function

Does anyone have an idea how a method / function is implemented Int()or floor()? I am looking for an appropriate implementation as shown below for a function abs().

Int Abs (float x){
  if x > 0 
      return x;
   else
      return -x
}

I'm struggling to find a solution for it without using the module operator.

+3
source share
4 answers

It seems to me,

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

gotta do the trick.

+16
source

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

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;
}
+3
source

"int" , :

int ifloor( float x )
{
    if (x >= 0)
    {
        return (int)x;
    }
    else
    {
        int y = (int)x;
        return ((float)y == x) ? y : y - 1;
    }
}
+1
private static int fastFloor(double x) {
    int xi = (int)x;
    return x < xi ? xi - 1 : xi;
}

, , - .

+1

Source: https://habr.com/ru/post/1794820/


All Articles