如何在给定整数和小数位置的情况下生成浮点数?
例如:
int decimal = 1000;
int decimal_position = 3;
float value = 1.000;我已经通过使用超能力做到了这一点,但效率不高。
decimal/pow(10, decimal_position)发布于 2018-02-25 02:42:30
如何在给定整数和小数位置的情况下生成浮点数?
我已经通过使用超能力做到了这一点,但效率不高。
float value = decimal/pow(10, decimal_position);它的范围取决于decimal_position的范围。
使用0 <= decimal_position < 8,代码可以使用表查找。
const float tens[8] = { 1.0f, 0.1f, ..., 1.0e-7f };
float value = decimal*tens[decimal_position];然而,要处理所有产生有限值的int decimal和int decimal_position,使用float powf(float )而不是double pow(double)应该是第一选择。
// float power function
float value = decimal/powf(10.0f, decimal_position);如果不是所需的最佳值,代码可以*。这稍微不太精确,因为0.1f不是精确的数学0.1。然而,*通常比/更快。
float value = decimal*powf(0.1f, decimal_position);对于较小的decimal_position值,可以进行循环以避免powf()
if (decimal_position < 0) {
if (decimal_position > -N) {
float ten = 1.0f;
while (++decimal_position < 0) ten *= 10.0f;
value = decimal*ten;
while (++decimal_position < 0) value /= 10.0f; // or value *= 0.1f;
} else {
value = decimal*powf(10.0f, -decimal_position);
}
} else {
if (decimal_position < N) {
float ten = 1.0f;
while (decimal_position-- > 0) ten *= 10.0f;
value = decimal/ten;
} else {
value = decimal/powf(10.0f, decimal_position); // alternate: *powf(0.1f, ...
}
}与powf()相比,部分处理器可能会从使用pow()中受益,但我发现powf()通常更快。
当然,如果int decimal和int decimal_position是这样的,那么整数答案是可能的:
// example, assume 32-bit `int`
if (decimal_position <= 0 && decimal_position >= -9) {
const long long[10] = {1,10,100,1000,..., 1000000000};
value = decimal*i_ten[-decimal_position];
} else {
value = use above code ... 或者,如果abs(decimal_position) <= 19和FP计算成本很高,请考虑:
unsigned long long ipow10(unsigned expo) {
unsigned long long ten = 10;
unsigned long long y = 1;
while (expo > 0) {
if (expo % 2u) {
y = ten * y;
}
expo /= 2u;
x *= ten;
}
return y;
}
if (decimal_position <= 0) {
value = 1.0f*decimal*ipow10(-decimal_position);
} else {
value = 1.0f*decimal/ipow10(decimal_position);
}或者如果abs(decimal_position) <= 27 ..。
if (decimal_position <= 0) {
value = scalbnf(decimal, -decimal_position) * ipow5(-decimal_position);
} else {
value = scalbnf(decimal, -decimal_position) / ipow5(decimal_position);
}https://stackoverflow.com/questions/48889655
复制相似问题