Matlab precision: simple subtraction is not zero

前端 未结 5 2018
野趣味
野趣味 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:43

    I do not know if it is applicable to your problem but often the simplest solution is to scale your data.

    For example:

    a=0.04;
    b=0.2;
    a-0.2*b
    ans=-6.9389e-018
    c=a/min(abs([a b]));
    d=b/min(abs([a b]));
    c-0.2*d
    ans=0
    

    EDIT: of course I did not mean to give a universal solution to these kind of problems but it is still a good practice that can make you avoid a few problems in numerical computation (curve fitting, etc ...). See Jim Clay's answer for the reason why you are experiencing these problems.

提交回复
热议问题