MATLAB Answers

ntclrz
0

How can I find if an element of my array is divisible with 0.05

ntclrz
さんによって質問されました 2019 年 3 月 28 日
最新アクティビティ John D'Errico
さんによって 回答されました 2019 年 3 月 28 日
Hello everybody,
I have this array:
A = [7.00 8.40 3.70 8.31 5.80]
I want to proove that every element in my array is divisible with 0.05 and as a result there are only integers. In this case 8.31 isn't and I would like that the script doesn't run any further and become an "error" in the command window. Is this possible?

  0 件のコメント

サインイン to comment.

1 件の回答

回答者: John D'Errico
2019 年 3 月 28 日
 採用された回答

Um, no. And, Yes.
Floating point numbers like 0.05 are NOT EXACTLY representable in double precision. Remember that doubles arestored in binary, not in decimal form. What actually gets stored is this:
sprintf('%0.55f',0.05)
ans =
'0.0500000000000000027755575615628913510590791702270507812'
In binary, it looks like a repeating fraction, where the mantissa looks like:
'0.000011001100110011001100110011001100110011001100110011010'
So we can write 0.05 as approximately:
sum(2.^[-5 -6 -9 -10 -13 -14 -17 -18 -21 -22 -25 -26 -29 -30 -33 -34 -37 -38 -41 -42 -45 -46 -49 -50 -53 -54 -56])
ans =
0.05
But that is only an approximation, not any different from the idea that 1/3 or 2/3 are not representable exactly as decimals. So, can you tell that 0.15, for example, is EXACTLY amultiple of 0.05? No.
The basic idea would be to divide each number by 0.05. If the result is exactly an integer, then it would be divisible by 0.05. So, we might try this:
x = 0.05:0.05:1;
notdiv = find(x/0.05 ~= round(x/0.05))
notdiv =
3 6 12 13 14 19
x(notdiv)
ans =
0.15 0.3 0.6 0.65 0.7 0.95
MATLAB thinks that those numbers are NOT divisible by 0.05. Wrong, of course.
Instead, we might use a tolerance.
notdiv = find(abs(x/0.05 - round(x/0.05)) > 100*eps)
notdiv =
1×0 empty double row vector
As you can see, this works a little better:
x = 0.01:0.01:0.10;
>> notdiv = find(abs(x/0.05 - round(x/0.05)) > 100*eps)
notdiv =
1 2 3 4 6 7 8 9
>> x(notdiv)
ans =
0.01 0.02 0.03 0.04 0.06 0.07 0.08 0.09
We might need to be careful about the tolerance employed there.

  0 件のコメント

サインイン to comment.



Translated by