Matlab Number Precision Affects the Results

3 Ansichten (letzte 30 Tage)
Berk Demir
Berk Demir am 22 Jan. 2020
Kommentiert: dpb am 22 Jan. 2020
Some numbers have 1 in their end after certain digits...
For example, -14.8 has following results if you format long. But some does not have this 1.
ans =
-14.800000000000001
>> -14.7
ans =
-14.699999999999999
>> -14.5
ans =
-14.500000000000000
Right now, in my code, I have following problem: I am creating an array between -26 and 26 with step size 0.01. Part of the results are as follows:
Columns 5182 through 5184
25.809999999999999 25.820000000000000 25.829999999999998
Columns 5185 through 5187
25.840000000000000 25.850000000000001 25.859999999999999
Columns 5188 through 5190
25.870000000000001 25.879999999999999 25.890000000000001
Columns 5191 through 5193
25.899999999999999 25.910000000000000 25.920000000000002
So, I need to check some values whether if they are member of this array, however, due to accumulation of precision error, I end up with NOT MEMBER result. So, how can I solve my problem?

Antworten (1)

dpb
dpb am 22 Jan. 2020
Use ismembertol instead. And read up on floating point precision at <What Need to Know About Floating Point>
  3 Kommentare
Guillaume
Guillaume am 22 Jan. 2020
It's not clear what error you are talking about. As far as I can tell, there is no error, this is just the way floating point numbers work.
You could round the numbers to two decimals, or whatever you need. However, again, due to the way floating point numbers work this may not always give you the result you expect. ismembertol (or any other tolerance based method) as per dpb answer is the proper way to compare your numbers.
dpb
dpb am 22 Jan. 2020
"I am creating an array between -26 and 26 with step size 0.01. ... is there a way to reduce this error?"
'Pends on how you're doing it. If rounding is occurring and accumulating, you may be using loop or other inefficient technique that does have numerical issues. Show code, we can't diagnose what we can't see.
NB: that 0.01 cannot be held in floating point exactly no matter what precision; the lower the precision the more noticeable rounding will be if you accumulate.
NB2: the built-in linspace function is designed to minimize the discrepancies that occur in the alternative methods; for your case use
x1=-26;
x2=-x1;
dx=0.01;
x=linspace(x1,x2,(x2-x1)/dx);

Melden Sie sich an, um zu kommentieren.

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by