是否有可能将 C 中调和级数的浮点和的精度提高到 10^-8 以上?

0 c algorithm floating-point series

给定谐波级数 1 - 1/2 + 1/3 - 1/4... = ln(2),是否可以仅使用浮点值并仅使用基本运算 (+、-、 ,/)。是否有任何算法可以提高此计算的精度,而不会达到不合理的高 n 值(当前合理限制为 1e^10)

我目前拥有的:这使我得到了 8 个正确的数字 -> 0.6931471825

编辑目标是仅使用浮点数据类型 计算最精确的求和值

int main()
{
    float sum = 0;
    int n = 1e9;
    double ans = log(2);
    int i;
    float r = 0;

    for (i = n; i > 0; i--) {
        r = i - (2*(i/2));
        if(r == 0){
            sum -= 1.0000000 / i;
        }else{
            sum += 1.0000000 / i; 
        }
    }

    printf("\n%.10f", sum);
    printf("\n%.10f", ans);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

ike*_*ami 5

在 afloat是单精度 IEEE 浮点数的系统上,它具有 24 位精度,大约为 7 或 (log 10 (2 24 )) 位十进制精度。

如果你改变

double ans = log(2);
Run Code Online (Sandbox Code Playgroud)

到

float ans = log(2);
Run Code Online (Sandbox Code Playgroud)

您会发现您已经获得了最佳答案。

0.6931471 82464599609375       From log(2), casted to float
0.6931471 82464599609375       From your algorithm
0.6931471 8055994530941723...  Actual value
  \_____/
  7 digits
Run Code Online (Sandbox Code Playgroud)

事实上,如果您使用%A代替%f,您会看到该位得到相同的答案。

0X1.62E43P-1  // From log(2), casted to float
0X1.62E43P-1  // From your algorithm
Run Code Online (Sandbox Code Playgroud)