花车是不精确 [英] Floats being Inexact

查看:134
本文介绍了花车是不精确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我百思不得其解。我也没有解释为什么本次测试使用双击数据类型时通过,但使用浮动数据类型时失败。考虑code的片断。

I am puzzled. I have no explanation to why this test passes when using the double data type but fails when using the float data type. Consider the following snippet of code.

float total = 0.00;

for ( int i = 0; i < 100; i++ ) total += 0.01;

照理为1.00,但它是等于0.99。为什么会出现这样的情况?我用GCC和铿锵编译,编译器都具有相同的结果。

One would anticipate total to be 1.00, however it is equal to 0.99. Why is this the case? I compiled with both GCC and clang, both compilers have the same result.

推荐答案

在十进制0.01的值是pssed作为该系列的前$ P $:A1 *(1/2)+ A2 *(1/2)^ 2 + A3 *(1/2)^ 4 +等,其中是0或1。

The value for 0.01 in decimal is expressed as the series: a1*(1/2) + a2*(1/2)^2 + a3*(1/2)^4 + etc. where aN is a zero or one.

我让你找出A1,A2和多少小数位()的要求的具体数值。在某些情况下,小数部分不能被重新用有限系列(1/2)^ n个值的psented $ P $

I leave it to you to figure out the specific values of a1, a2 and how many fractional bits (aN) are required. In some cases a decimal fraction cannot be represented by a finite series of (1/2)^n values.

有关这一系列来总结,以小数0.01需要一个超越(存储在一个浮的位数比特的全字减去比特为一个数签署和指数)。但由于双有更多的位,然后0.01小数可以/也许/也许(你们做计算)是precisely定义。

For this series to sum to 0.01 in decimal requires that aN go beyond the number of bits stored in a float (full word of bits minus the number of bits for a sign and exponent). But since double has more bits then 0.01 decimal can/might/maybe (you do the calculation) be precisely defined.

这篇关于花车是不精确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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