3

我尝试遵循“自然对数 (ln) 和求幂的有效实现”主题,以便能够在没有 math.h 的情况下实现对数函数。所描述的算法适用于 1 和 2 之间的值(归一化值)。但是,如果这些值没有被规范化并且我按照规范化说明进行操作,那么我会得到错误的值。

链接:点这里

如果我遵循示例整数值 12510 的代码,我会得到以下结果:

y = 12510 (0x30DE),log2 = 13,除数 = 26,x = 481,1538

float ln(float y) {
    int log2;
    float divisor, x, result;

    log2 = msb((int)y); // See: https://stackoverflow.com/a/4970859/6630230
    divisor = (float)(1 << log2);
    x = y / divisor;    // normalized value between [1.0, 2.0]

    result = -1.7417939 + (2.8212026 + (-1.4699568 + (0.44717955 - 0.056570851 * x) * x) * x) * x;
    result += ((float)log2) * 0.69314718; // ln(2) = 0.69314718

    return result;
}

x 的预期结果应该是 1 < x < 2 的标准化值。但是,我在这个计算中失败了,因为收到的结果是 481,1538。

提前感谢您的帮助

4

1 回答 1

5

出于好奇,我试图重现:

#include <stdio.h>

int msb(unsigned int v) {
  unsigned int r = 0;
  while (v >>= 1) r++;
  return r;
}

float ln(float y)
{
    int log2;
    float divisor, x, result;

    log2 = msb((int)y); // See: https://stackoverflow.com/a/4970859/6630230
    printf("log2: %d\n", log2);
    divisor = (float)(1 << log2);
    printf("divisor: %f\n", divisor);
    x = y / divisor;    // normalized value between [1.0, 2.0]
    printf("x: %f\n", x);
    result = -1.7417939 + (2.8212026 + (-1.4699568 + (0.44717955 - 0.056570851 * x) * x) * x) * x;
    result += ((float)log2) * 0.69314718; // ln(2) = 0.69314718
    return result;
}

int main()
{
  printf("ln(12510): %f\n", ln(12510));
}

输出:

log2: 13
divisor: 8192.000000
x: 1.527100
ln(12510): 9.434252

coliru 现场演示

我刚刚在我的 Windows 7 袖珍计算器中尝试过这个并得到:

9.434283603460956823997266847405

9,434283603460956823997266847405

前 5 位数字相同。– 其余的我会认为是四舍五入的问题,而不知道哪个更接近。

但是,问题中有一个错字(或错误):

y = 12510 (0x30DE),log2 = 13,除数 = 26,x = 481,1538

divisor = (float)(1 << log2);log2 = 13产量8192

log2 << 1会导致26.

只是为了好玩,我将线路更改为divisor = (float)(log2 << 1);并得到以下输出:

log2: 13
divisor: 26.000000
x: 481.153839
ln(12510): -2982522368.000000

所以,这让我有点困惑:

暴露的代码似乎是正确的,但 OP 似乎将其解释(或类似)错误。

于 2019-10-26T12:50:32.890 回答