问题
Does anyone have an idea how is the method/function Int()
or floor()
implemented?
What I am looking for a respective implementation as the following is for abs()
function.
Int Abs (float x){
if x > 0
return x;
else
return -x
}
I am struggling to find a solution for it without using the modulus operator.
回答1:
Seems to me like
floor(n) = n - (n % 1)
should do the trick.
回答2:
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;
}
回答3:
private static int fastFloor(double x) {
int xi = (int)x;
return x < xi ? xi - 1 : xi;
}
This is a method similar to Michal Crzardybons answer but it avoids a conditional branch and still handles negative numbers properly.
回答4:
If result of type 'int' is enough, then 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;
}
}
回答5:
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 at x=0.5-2^-54
note: logical operations are assumed to convert to integer values 1 for true and 0 for false
Implementations are done so they match the domains defined in int(x), floor(x), ceil(x) and round(x)
来源:https://stackoverflow.com/questions/5122993/floor-int-function-implementaton