假设我有一个浮点数。我想提取数字的基数2表示中的所有一位数字的位置。
例如,10.25 =2^2+ 2^1 + 2^3,因此它的基-2位置是{-2,1,3}。
一旦我得到了一个数n的以2为底的幂的列表,下面的代码应该总是返回true (伪代码)。
sum = 0
for power in powers:
sum += 2.0 ** power
return n == sum然而,在C和C++中对浮点数执行位逻辑有些困难,更难的是可移植性。
在这两种语言中,如何用少量的CPU指令来实现这一点呢?
发布于 2012-08-04 09:39:41
不需要对浮点数进行编码。C提供了以可移植的方式处理浮点值的例程。以下是有效的方法。
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
/* This should be replaced with proper allocation for the floating-point
type.
*/
int powers[53];
double x = atof(argv[1]);
if (x <= 0)
{
fprintf(stderr, "Error, input must be positive.\n");
return 1;
}
// Find value of highest bit.
int e;
double f = frexp(x, &e) - .5;
powers[0] = --e;
int p = 1;
// Find remaining bits.
for (; 0 != f; --e)
{
printf("e = %d, f = %g.\n", e, f);
if (.5 <= f)
{
powers[p++] = e;
f -= .5;
}
f *= 2;
}
// Display.
printf("%.19g =", x);
for (int i = 0; i < p; ++i)
printf(" + 2**%d", powers[i]);
printf(".\n");
// Test.
double y = 0;
for (int i = 0; i < p; ++i)
y += ldexp(1, powers[i]);
if (x == y)
printf("Reconstructed number equals original.\n");
else
printf("Reconstructed number is %.19g, but original is %.19g.\n", y, x);
return 0;
}https://stackoverflow.com/questions/11803644
复制相似问题