# Unexpected result from linspace function

5 Ansichten (letzte 30 Tage)
Rostislav Teryaev am 15 Aug. 2018
Kommentiert: Dyuman Joshi am 9 Dez. 2023
Why the result of this code
B1 = 0:0.1:1.8;
B2 = linspace(0,1.8,19)
B1(4)-0.3
B2(4)-0.3
is 5.5511e-17? I found a workaround, which is
B1 = 0:01:18;
B1 = B1/10;
But I am still wondering why the first code does not produce what it should?
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Rik am 15 Aug. 2018
Welcome to the wondrous world of floating point numbers. Matlab is a computer program, so it works with binary. Some values are impossible to represent in a binary expansion, so they get rounded. This can be different for each algorithm, so even if the end result can be represented, rounding errors can build up. That is the use case for the eps function: it shows you what the magnitude is of possible errors.
As a decimal example, consider this: (1/3)*3. Assuming I can only store 2 decimal digits, that would be 0.33*3=0.99, even if the correct answer doesn't need 2 decimals.
##### 9 Kommentare7 ältere Kommentare anzeigen7 ältere Kommentare ausblenden
Stephen23 am 9 Dez. 2023
"Is there any work around to deal with floating point arithmetic problems in matlab ?"
The problem is not "in MATLAB", it is simply how your computer stores floating point numbers. MATLAB runs on your computer: if there was a simple "work around" then everyone would use it, not just MATLAB.
You can certainly use symbolic or high precision classes, but then your code will be much slower.
Dyuman Joshi am 9 Dez. 2023
"Is there any workaround to deal with floating point arithmetic problems?"
@VIGNESH BALAJI - There, I fixed the question for you.
Certainly, one option is to use a computer that runs on a decimal system. There might be a lot of complications, though.
As long as you use computers that use the binary system, you will encounter floating point errors.
Rik and Stephen have already provided suggestions as to what you can do as workarounds, I'll just reiterate them -
You can avoid using floats.
Well, what to use then? Symbolic numbers or high precision classes, which work at the cost of the code performance.

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Logical finden Sie in Help Center und File Exchange

R2018a

### Community Treasure Hunt

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

Start Hunting!

Translated by