Least integer function and Greatest Integer Function Without using ceil() and Floor()

1k Views Asked by At

I was wondering if there is any mathematical way to calculate Least Integer and Greatest integer without using predefined Ceil() and Floor() Function of Programming Language.

1

There are 1 best solutions below

1
On

You got good advise in the comments by TravisJ. You should not try to implement the simple math functions (sin,cos,exp,floor, etc.) yourself unless you really know what you are doing. These functions have been so optimized that beating them on speed is almost impossible (unless you can do with lower accuracy).


However, there is a 'simple' way to compute the floor (or ceil) by directly manipulating the binary representation of the number:

$$a = (-1)^{\text{sign}}(1.b_{51}b_{50}...b_{0})_2 \times 2^{e-1023}$$

Just for fun, here is a method, made by a collegue of mine, that does this in c/c++:

int64_t myfloor(double a) {
  // a = sign * frac * 2^exp
  uint64_t raw = *(uint64_t*) &a;
  int sign = raw >> 63;
  int exp  = (int)(( raw >> 52) & 0x7ff ) - 0x3ff - 52;
  uint64_t frac = 1ull << 52 | raw & 0xfffffffffffffull;
  frac <<= 1;
  if(exp>=0) frac <<= exp;
  else frac >>= -exp;
  if(sign) frac += 1;
  frac >>= 1;
  return sign ? -(int64_t) frac : (int64_t) frac;
}

This method is, as you can test for yourself, much slower then the built-in method.