相关疑难解决方法(0)

浮点数学是否破碎?

请考虑以下代码:

0.1 + 0.2 == 0.3  ->  false
Run Code Online (Sandbox Code Playgroud)
0.1 + 0.2         ->  0.30000000000000004
Run Code Online (Sandbox Code Playgroud)

为什么会出现这些不准确之处?

language-agnostic math floating-point floating-accuracy

2798
推荐指数
28
解决办法
28万
查看次数

处理浮点数中的精度问题

我想知道是否有办法克服精确度问题,这似乎是我的机器内部表示浮点数的结果:

为清楚起见,问题归纳为:

// str is "4.600";   atof( str ) is 4.5999999999999996  
double mw = atof( str )  

// The variables used in the columns calculation below are:   
//  
//                    mw = 4.5999999999999996  
//                    p = 0.2  
//                    g = 0.2  
//                    h = 1 (integer)  

int columns = (int) ( ( mw - ( h * 11 * p ) ) / ( ( h * 11 * p ) + g ) ) + 1;
Run Code Online (Sandbox Code Playgroud)

在转换为整数类型之前,列计算的结果是1.9999999999999996; 距离2.0的理想结果还差不多.

任何建议最受欢迎.

c++ floating-point floating-accuracy

9
推荐指数
5
解决办法
1万
查看次数