Arithmetic precision with doubles in Matlab

前端 未结 3 1066
礼貌的吻别
礼貌的吻别 2021-01-19 02:18

I am having a bit of trouble understanding how the precision of these doubles affects the outcome of arithmetic operations in Matlab. I thought that since both a & b are

3条回答
  •  -上瘾入骨i
    2021-01-19 02:43

    To add to what the other answers have said, you can use the MATLAB function EPS to visualize the precision issue you are running into. For a given double-precision floating-point number, the function EPS will tell you the distance from it to the next largest representable floating point number:

    >> a = 1.22e-45;
    >> b = 1;
    >> eps(b)
    
    ans =
    
      2.2204e-016
    

    Note that the next floating point number that is larger than 1 is 1.00000000000000022204..., and the value of a doesn't even come close to half the distance between the two numbers. Hence a+b ends up staying 1.

    Incidentally, you can also see why a is considered non-zero even though it is so small by looking at the smallest representable double-precision floating-point value using the function REALMIN:

    >> realmin
    
    ans =
    
      2.2251e-308  %# MUCH smaller than a!
    

提交回复
热议问题