Matlab accuracy (when 1-1~=0)

4 views (last 30 days)
Damian Maxwell
Damian Maxwell on 20 Sep 2022
Commented: Damian Maxwell on 21 Sep 2022
Below please find a screenshot from a sample script that really puzzles me.
When defining simple variables and then substracting them there appear to be tiny error (3e-18) that comes in with surprising results.
It would be great if somebody could explain why this happens and how to avoid it.
w=0.026
b=0.024
i=0.001
w-0.026
b-0.024
i-0.001
w-(b+2*i)
w==(b+2*i)

Answers (1)

Eric Delgado
Eric Delgado on 20 Sep 2022
Edited: Eric Delgado on 20 Sep 2022
It's float operation universe. :)
w=0.026;
b=0.024;
i=0.001;
w-0.026;
b-0.024;
i-0.001;
Instead of:
w == (b+2*i)
ans = logical
0
Use:
abs(w - (b+2*i)) <= 1e-5 % You could use 1e-17 and still will receive a true logical value
ans = logical
1
  5 Comments
Damian Maxwell
Damian Maxwell on 21 Sep 2022
Thank you so much Walter for the clear explanation.

Sign in to comment.

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by