1208 float 浮点数 加减乘除 取整 3

自己随便写了一下,觉得好像还可以,很多变量可以省略,只是方便我单步调试跟踪而已。
float round_floatsf(float  f,int bits)
&leftsign; www.yippeesoft.com
 double ii=0.5;
 double jj=0.1;
 int  n=10;
 for (int i=1;i<bits;i++)
 &leftsign;
  jj=jj*0.1;
  n=n*10;
 &rightsign;
 ii=ii*jj;
 float g=f+ii;
 int iii=((int)(g*n+0.5));
 float tt=(float)iii*jj;
 return tt;
&rightsign; www.yippeesoft.com

f:      1.240500        ss:1.241000
f:      1.241500        ss:1.242000
f:      1.242500        ss:1.243000
f:      1.243500        ss:1.244000
f:      1.244500        ss:1.245000
f:      1.245500        ss:1.246000
f:      1.246500        ss:1.247000
f:      1.247500        ss:1.248000
f:      1.248500        ss:1.249000
f:      1.249500        ss:1.250000

MVP的Bruno Jouhier的回答:

The problem is that 0.1 cannot be represented **exactly** as a float
(surprise!) www.yippeesoft.com

Float (and double) can only represent exactly numbers that can be written as
m * 2^e where m and e are integers (possibly negative).
Numbers like 0.5, 0.25, 0.125 or 0.875 are exactly representable as floats
(1*2^-1, 1*2^-2, 1^2-3, 7*2^-3) but 0.1 is not (its binary representation is
infinite)!

So, 0.1f is only an approximation of 0.1 and the error will accumulate when
you add.
0.1不能被正确的表现为float类型,只有能被写成m*2^e(m和e都是int型的,负数也可以)表示的才是真正意义上的浮点数,这样的数才不会造成我们使用时累加时出现error accumulate的情况。

浮点数的内存结构  www.yippeesoft.com
根据IEEE的标准,浮点数的定义如下
             符号位   指数位       小数部分      指数偏移量
单精度浮点数 1 位[31] 8位 [30-23]  23位 [22-00]  127
双精度浮点数 1 位[63] 11 位[62-52] 52 位[51-00]  1023

简而言之,FLOAT浮点数精确表达有问题 www.yippeesoft.com

1. 即使在表达范围内,浮点数(float、double、long double)也不能精确表达每一个实数。
比如float可以精确表达67.0f,可以精确表达6.69999980926513671875f,但不能精确表达6.7f。
当不能精确表达时,选择一个最接近的能精确表达的数,比如float以6.69999980926513671875f来表达6.7f。
2. 浮点数计算使用80387数字协处理器,把每一个浮点数载入80bits的临时实数中,进行计算,结果然后再放回。
3. 高精度浮点数转化为低精度浮点数时,使用低精度浮点数能表示的最接近的数;浮点数转化为整型时,直接取整数部分。

历史博文

标签:,
十二月 17, 2005 at 4:35 下午 by yippee 1,025 次
Category: Dev
Tags: ,