为什么没有错误,同时乘以浮点数? [英] Why there is no errors while multiplying floating point numbers?

查看:131
本文介绍了为什么没有错误,同时乘以浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关浮点运算的一些clearification。

I need some clearification about floating point math.

我已经写了一些code为学习的效果影响不大:

I have wrote some code for the learning purpouses:

#include "stdio.h"

int main (int argc, char const *argv[])
{
    int i;
    double a=1.0/10.0;
    double sum=0;

    for(i = 0; i < 10; ++i)
        sum+=a;

    printf("%.17G\n", 10*a );
    printf("%d\n", (10*a == 1.0) );

    printf("%.17G\n", sum );
    printf("%d\n", (sum == 1.0) );

    return 0;
}

和它给人的输出是:

    1
    1
    0.99999999999999989
    0

为什么?(总和== 1.0) - 是假的是pretty understandabale,但为什么乘法没有给出错误的正确答案

Why (sum == 1.0) - is false is pretty understandabale, but why multiplying gives the right answer without the error?

感谢。

推荐答案

在执行反复此外,还有9圆角正在发生:第一个结果 A + A 是总是精确重新presentable,但在此之后,再加入是不精确由于加数的基-2-指数不相等。

When performing the repeated addition, there are 9 roundings taking place: the first result a+a is always exactly representable, but after that, further additions are inexact since the base-2 exponents of the addends are not equal.

在执行乘法,这里只有一个舍入,这恰好给你你想要的结果。

When performing the multiplication, there's only a single rounding, and it happens to give you the result you wanted.

这篇关于为什么没有错误,同时乘以浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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