Info

此问题已关闭。 请重新打开它进行编辑或回答。

Hi.I have been trying a lot to "find" the answer. I still can not get it.

1 次查看(过去 30 天)
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 个评论
Guillaume
Guillaume 2018-6-25
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.

回答(1 个)

John D'Errico
John D'Errico 2018-6-25
编辑:John D'Errico 2018-6-25
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.)

此问题已关闭。

产品

Community Treasure Hunt

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

Start Hunting!

Translated by