调用舍入的结果差异时,POW() [英] Differences in rounded result when calling pow()

查看:177
本文介绍了调用舍入的结果差异时,POW()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OK,我知道有关于战俘的功能和铸造它的结果为int很多问题,但我无法找到答案,这一点具体的问题。

OK, I know that there was many question about pow function and casting it's result to int, but I couldn't find answer to this a bit specific question.

OK,这是C code:

OK, this is the C code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    int i = 5;
    int j = 2;

    double d1 = pow(i,j);
    double d2 = pow(5,2);
    int i1 = (int)d1;
    int i2 = (int)d2;
    int i3 = (int)pow(i,j);
    int i4 = (int)pow(5,2);

    printf("%d %d %d %d",i1,i2,i3,i4);

    return 0;
}

这是输出:25 25 24 25。请注意,只有在第三种情况下,其中的参数战俘都没有文字,我们有一个错误的结果,可能是由舍入错误引起的。同样的事情happends没有明确的铸造。可能有人解释这4箱子会发生什么?

And this is the output: "25 25 24 25". Notice that only in third case where arguments to pow are not literals we have that wrong result, probably caused by rounding errors. Same thing happends without explicit casting. Could somebody explain what happens in this four cases?

即时通讯使用$ C $的cblock在Windows 7中,和MinGW gcc编译器与它来了。

Im using CodeBlocks in Windows 7, and MinGW gcc compiler that came with it.

推荐答案

POW 操作的结果是25.0000正负舍入误差的一些位。如果舍入误差是正或0,25,将导致从转换为整数。如果舍入误差是负的,24将导致。这两个答案都是正确的。

The result of the pow operation is 25.0000 plus or minus some bit of rounding error. If the rounding error is positive or zero, 25 will result from the conversion to an integer. If the rounding error is negative, 24 will result. Both answers are correct.

什么是最可能的内部的动作是在一种情况下一个higher- precision,80位的FPU值被直接使用,并且在其他情况下,结果是从FPU的存储器写入(作为64位双),然后在(将其转换为一个稍微不同的80位的值)读回。这可以使在最终结果的显微镜差异,这是所有需要一个25.0000000001改变到24.999999997

What is most likely happening internally is that in one case a higher-precision, 80-bit FPU value is being used directly and in the other case, the result is being written from the FPU to memory (as a 64-bit double) and then read back in (converting it to a slightly different 80-bit value). This can make a microscopic difference in the final result, which is all it takes to change a 25.0000000001 to a 24.999999997

另一种可能是你的编译器可以识别传递给 POW 常量并执行计算本身,替换结果为调用 POW 。你的编译器可能会使用内部arbitrary- precision数学库也可能只使用一个是不同的。

Another possibility is that your compiler recognizes the constants passed to pow and does the calculation itself, substituting the result for the call to pow. Your compiler may use an internal arbitrary-precision math library or it may just use one that's different.

这篇关于调用舍入的结果差异时,POW()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆