Info
This question is closed. Reopen it to edit or answer.
Hi.I have been trying a lot to "find" the answer. I still can not get it.
1 view (last 30 days)
Show older comments
I have a MATLAB function which uses the FIND command, and when I use the same function in Simulink I am getting an error. Can someone please tell me how to implement FIND command in Simulink?
4 Comments
Guillaume
on 25 Jun 2018
Unrelated to your question (which I can't answer since I don't know simulink), but ultimately probably more important, it looks like you need to learn about floating point comparison. Read this to learn more.
A more reliable code would be:
x1 = (0:0.001:50 )';
lperc = find(abs(px - x1) <= 1e-8); %arbitrary small value much smaller than the precision of x1.
Answers (1)
John D'Errico
on 25 Jun 2018
Edited: John D'Errico
on 25 Jun 2018
The error? Yours, in making an assumption about floating point arithmetic, and how numbers are stored.
x1=(0:0.001:50 )';
x1 = round(x1,3 );
Now, lets look at x1(2), for example. The same will apply to nearly every other element in x1.
x1(2)
ans =
0.001
It looks like 0.001. But is it?
sprintf('%0.55f',x1(2))
ans =
'0.0010000000000000000208166817117216851329430937767028809'
Almost all such floating point numbers cannot by exactly stored, because you are creating decimal fractions, but storing them in binary form.
Just as you cannot represent 1/3 exactly as a decimal number, you cannot represent 0.001 exactly in binary form, using a finite number of binary bits. While it looks like 1/1000 to you, in binary form, it will be a infinitely repeating string of binary bits.
That rounding operation did not in fact round numbers to exactly 3 places.
So NEVER test for exact equality of floating point numbers. Use a tolerance instead. (If you know what you are doing, and know when it is safe, integers can be tested for equality, even when the integers are doubles, within limits.)
0 Comments
This question is closed.
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!