Matlab precision: simple subtraction is not zero

前端 未结 5 1990
野趣味
野趣味 2021-01-16 13:20

I compute this simple sum on Matlab:

2*0.04-0.5*0.4^2 = -1.387778780781446e-017

but the result is not zero. What can I do?

5条回答
  •  遥遥无期
    2021-01-16 13:58

    Aabaz and Jim Clay have good explanations of what's going on.

    It's often the case that, rather than exactly calculating the value of 2*0.04 - 0.5*0.4^2, what you really want is to check whether 2*0.04 and 0.5*0.4^2 differ by an amount that is small enough to be within the relevant numerical precision. If that's the case, than rather than checking whether 2*0.04 - 0.5*0.4^2 == 0, you can check whether abs(2*0.04 - 0.5*0.4^2) < thresh. Here thresh can either be some arbitrary smallish number, or an expression involving eps, which gives the precision of the numerical type you're working with.

    EDIT: Thanks to Jim and Tal for suggested improvement. Altered to compare the absolute value of the difference to a threshold, rather than the difference.

提交回复
热议问题