How to get rid of small difference (or error) when I multiply 0.1?

2 Ansichten (letzte 30 Tage)
Let's say I have an array. The difference between numbers is 1.
If I use a function 'diff' with 'unique', then I know whether the array is increasing or decreasing the constant amount.
ls = [1:10]'
unique(diff(ls))
%% ans = 1
In the above code, the answer is 1 obviously.
However, if I multiply 0.1 to the array, suddenly it does not work anymore.
I expected 'numel(unique(diff(ls * 0.1)))' gives '1' and the value is 0.1
However, Matlab says there are four different steps.
unique(diff(ls * 0.1))
%% ans =
% 0.1000
% 0.1000
% 0.1000
% 0.1000
I guess this is due to small precision. If I divide the array with a prime number then I understand the results. However, in this case, it is a very simple calculation, dividing by 10.
Why it happens? or how can I solve this problem?

Akzeptierte Antwort

Matt J
Matt J am 24 Jun. 2021
Bearbeitet: Matt J am 24 Jun. 2021
Use uniquetol(), e.g.,
ls=1:10;
uniquetol(diff(ls*0.1),1e-5)
ans = 0.1000

Weitere Antworten (1)

John D'Errico
John D'Errico am 24 Jun. 2021
You do understand that MATLAB, as is true of almost any programming language, uses binary storage methods to store all floating point numbers. This is something you want, because it makes your computer really fast and efficient.
It also means, just as you cannot represent 1/3 exactly as a finite length decimal number, you cannot represent 1/10 as a finite length BINARY number.
If you tried that, it would look something like the infinitely repeating binary number:
0.00011001100110011001100110011001100110011001100110011010.....
where the ones represent negative powers of 2.
And that means you CANNOT expect MATLAB to get what you are trying to do right.
Instead, learn to use tolerances when you test for such tiny differences.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by