Incrementing value within stateflow loop never equals the desired condition

6 views (last 30 days)
I have a loop within my stateflow that increments the variable N from 0. In the first state I have N=N and then the next state I have N=N+0.1. The condition I have to exit the loop is that N==1||N==2||N==3 as I need these values to be input into a sine function. It is not acceptable to change the condition to be N>=1 because I am no longer able to reenter the loop and receive the values of 2 and 3. Is there a way to make the state realize when N=1,2,3 such that it exits the loop? For some reason it just keeps increasing past these values, making it seem like the condition is never met when it should be.
Thanks, Craig

Answers (1)

Kyle Heintz
Kyle Heintz on 17 May 2018
Hello Craig,
The behavior you are seeing is due to a computer's limited ability to represent numbers in memory. All floating point numbers are stored as base-2, or binary fractions. The number 0.1, or 1/10th, can not be represented in binary so when 0.1 is stored in memory there is some round-off error. Repeated additions of 0.1 will compound this imprecision leading to a potentially inaccurate number.
You can see this effect by executing the following commands in MATLAB:
x = 0.1 + 0.1 + 0.1;
x == 0.3
The second command above should output 0 (false) because the stored value for x is slightly larger than 0.3.
One way you could work around this phenomenon in your Stateflow chart is by incrementing N by 1 instead. Then when checking for exit conditions, you can multiply N by the increment value. For example:
if N*0.1==1
% do something
end
For more details on the accuracy of floating-point numbers, refer to the following blog post:

Categories

Find more on Stateflow in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!