What is the difference between float and double?

前端 未结 13 977
悲哀的现实
悲哀的现实 2020-11-22 06:00

I\'ve read about the difference between double precision and single precision. However, in most cases, float and double seem to be interchangeable,

13条回答
  •  借酒劲吻你
    2020-11-22 06:02

    I just ran into a error that took me forever to figure out and potentially can give you a good example of float precision.

    #include 
    #include 
    
    int main(){
      for(float t=0;t<1;t+=0.01){
         std::cout << std::fixed << std::setprecision(6) << t << std::endl;
      }
    }
    

    The output is

    0.000000
    0.010000
    0.020000
    0.030000
    0.040000
    0.050000
    0.060000
    0.070000
    0.080000
    0.090000
    0.100000
    0.110000
    0.120000
    0.130000
    0.140000
    0.150000
    0.160000
    0.170000
    0.180000
    0.190000
    0.200000
    0.210000
    0.220000
    0.230000
    0.240000
    0.250000
    0.260000
    0.270000
    0.280000
    0.290000
    0.300000
    0.310000
    0.320000
    0.330000
    0.340000
    0.350000
    0.360000
    0.370000
    0.380000
    0.390000
    0.400000
    0.410000
    0.420000
    0.430000
    0.440000
    0.450000
    0.460000
    0.470000
    0.480000
    0.490000
    0.500000
    0.510000
    0.520000
    0.530000
    0.540000
    0.550000
    0.560000
    0.570000
    0.580000
    0.590000
    0.600000
    0.610000
    0.620000
    0.630000
    0.640000
    0.650000
    0.660000
    0.670000
    0.680000
    0.690000
    0.700000
    0.710000
    0.720000
    0.730000
    0.740000
    0.750000
    0.760000
    0.770000
    0.780000
    0.790000
    0.800000
    0.810000
    0.820000
    0.830000
    0.839999
    0.849999
    0.859999
    0.869999
    0.879999
    0.889999
    0.899999
    0.909999
    0.919999
    0.929999
    0.939999
    0.949999
    0.959999
    0.969999
    0.979999
    0.989999
    0.999999
    

    As you can see after 0.83, the precision runs down significantly.

    However, if I set up t as double, such an issue won't happen.

    It took me five hours to realize this minor error, which ruined my program.

提交回复
热议问题