可能重复:
处理浮点数中的精度问题
而99.99*0.01 = 0.99
显然这是一个古老的浮点舍入问题,但是这种情况下的舍入误差对我来说似乎很大; 我的意思是我可能预期结果为0.99990000001或某些类似的'接近'结果.
为了记录,我在JavaVM和.Net环境中得到了相同的答案.
当我尝试对下面的类进行单元测试时,我得到以下舍入错误:
class TypeTotal
    attr_reader  :cr_amount,  :dr_amount,
                 :cr_count,  :dr_count
    def initialize()
        @cr_amount=Float(0);    @dr_amount=Float(0)
        @cr_count=0;            @dr_count= 0
    end
    def increment(is_a_credit, amount, count=1)
        case is_a_credit        
         when true
            @cr_amount = Float(amount)+ Float(@cr_amount)
            @cr_count += count
         when false
            @dr_amount = Float(amount)+ Float(@dr_amount)
            @dr_count += count
        end
    end
end
单元测试:
require_relative 'total_type'
require 'test/unit'
class TestTotalType < Test::Unit::TestCase 
  #rounding error
  def test_increment_count()
    t = TypeTotal.new()
       t.increment(false, 22.22, 2)       
       t.increment(false, 7.31, 3) 
     assert_equal(t.dr_amount, 29.53)    
  end
end
输出:
  1) Failure:
test_increment_count(TestTotalType) [total_type_test.rb:10]:
<29.529999999999998> expected but was …在Intel(R)Core(TM)i7-4790上运行这段代码,我得到了奇怪的结果:
#include <stdio.h>
#define CALCULUS 2052 - 1.0 - margin
void main(void)
{
    float margin = 1.0001;
    float a = CALCULUS;
    printf("%2.6f\t%2.6f\n", a, CALCULUS);
}
我有
$ gcc test2.c && ./a.out
2050.000000 2049.999900
有人可以解释这种行为吗?我知道,当我使用它不会发生double,而不是float,但我觉得奇怪的舍入发生在这样一个小数目.
不知道为什么,但如果我将大到小的 fp 数字相加,似乎增量误差会更大:
#include <iostream>
#include <math.h>
int main() {
    std::cout.precision(50);
    const int numLoops = 1000;
    const long length = 10000;
    const double rate = 0.1;
    long totalLength = length * numLoops;
    long long steps = (long long)(totalLength / rate);
    double sum = 0.0;
    double sumRemainder = 0.0;
    for (long long step = 0; step < steps; step++) {
        if (sumRemainder >= length) {
            sumRemainder = fmod(sumRemainder, length);
        }
        sum += rate;
        sumRemainder += rate;
    }
    std::cout << …当我将数据存储在变量/列中时,我在数据准确性方面存在问题.
请考虑以下示例
DECLARE @w NUMERIC(38, 15) = 0.458441,
        @a NUMERIC(38, 15) = 10.000000,
        @p NUMERIC(38, 15) = 5.000000
select  (1+0.458441)*(1+    10.000000/100)*(1+  5.000000/100) 
结果:( 1.68449935500000000000000000正确)
SELECT ( 1 + @w ) * ( 1 + @a / 100.0 ) * ( 1 + @p / 100.0 ) 
结果:( 1.684499不正确)
当我将值存储在变量中以及如何修复它时,任何人都能说出近似的原因是什么?