Unexpected for loop behaviour

2 visualizzazioni (ultimi 30 giorni)
Utkarsh Nipane
Utkarsh Nipane il 9 Lug 2019
This for loop is supposed to run for 2 iterations i.e. for i=0 and i=-0.1 as variable outputOverVoltageChange_65 = -0.1. Why is it running for only i=0?
  2 Commenti
Renato SL
Renato SL il 9 Lug 2019
I assume you post this question because in the output you get, there is only 1 set of entry but you expect 2.
So, can you post a screenshot/photo of the output and highlight the fact that there is only 1 entry there?
Thank you.
Walter Roberson
Walter Roberson il 9 Lug 2019
Your variable is not exactly what you think it is, or 0:-0.1:something does not generate exactly the values you expect. Remember that 0.1 cannot be exactly represented in binary floating point.

Accedi per commentare.

Risposta accettata

Stephen23
Stephen23 il 9 Lug 2019
Modificato: Stephen23 il 9 Lug 2019
"Unexpected for loop behaviour"
The value -0.1 cannot be represented exactly using floating point numbers, and you could quite easily be using different values of "-0.1", even though you think that they are the same value:
>> V = -0.1
V =
-0.1000
>> V = V+eps
V =
-0.1000
>> fprintf('%.30f\n',V)
-0.099999999999999784000000000000
>> 0:-0.1:V
ans =
0
What you see printed in the command window is the closest representation to 5 or 16 significant digits, depending on your current format setting. To see the "real" value download James Tursa's FEX submission:
Use James Tursa's num2strexact and you will see that none of those values really have the exact value -0.1. All you are looking at is a representation of those floating point numbers displayed in the command window, to the precision defined by your format setting. Just because you see -0.1 displayed tells you nothing about the "real" floating point number's value.
Note that you can change how the value is displayed by changing the format.
You need to learn about the limits of floating point numbers. Start by reading these:
This is worth reading as well:
  1 Commento
Utkarsh Nipane
Utkarsh Nipane il 9 Lug 2019
Thanks a lot for your prompt response. I checked the variable value in the workspace and it was actually greater than -0.1 (to be exact -0.099999999999994), that's why the loop was not working as expected. The main problem happening here is that the exact value of 0.1 is sometimes greater and sometimes smaller than 0.1, thus some loops implemented with same logic were working and some were not. At last thank you for providing me all these useful links, it will surely help me in rectifying my errors.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by