1×0 empty double row vector using find
36 次查看(过去 30 天)
显示 更早的评论
Hi, I have problem with this code:
clc; clear; close all
x=[0 0.1 0.2 0.3 0.4 0.5];
y=[1 7 4 3 5 2];
h=0.1;
n=(max(x)-min(x))/h
suma=0;
for i=2:n
aux=h*(i-1)
[row,col] = find(x==aux)
suma=suma+y(col);
end
when I run the for cicle and aux is equal to 0.3, the result of find is "1×0 empty double row vector", but there is a 0.3 in x. I'm really confused about this, someone can help me, please?
Thanks in advance.
回答(2 个)
James Tursa
2023-6-1
编辑:James Tursa
2023-6-1
Welcome to the world of floating point arithmetic. For your specific example, they are not equal. E.g.,
x=[0 0.1 0.2 0.3 0.4 0.5];
h=0.1;
i = 4;
aux=h*(i-1);
[row,col] = find(x==aux)
fprintf('%20.18f\n',x(4))
fprintf('%20.18f\n',aux)
isequal(0.3,3*0.1)
You can see that these numbers are close but not exactly equal. They differ by one least significant bit in the floating point bit pattern:
num2hex(0.3)
num2hex(3*0.1)
To understand why you get this difference between 0.3 and 3*0.1, see this link:
It is usually bad practice to test for exact equality when floating point arithmetic is involved. Your code needs to be written to account for these small differences.
0 个评论
VBBV
2023-6-1
clc; clear; close all
x=[0 0.1 0.2 0.3 0.4 0.5];
y=[1 7 4 3 5 2];
h=0.1;
n=(max(x)-min(x))/h
suma=0;
for i=2:n
aux=h*(i-1)
[row,col] = find((x==round(aux,1)))
suma=suma+y(col);
end
3 个评论
John D'Errico
2023-6-1
Be careful with rounding decimals. Even then, you do not get exactly what you think you get. For example,
x = 0.3;
sprintf('%0.55f',x)
y = round(x,1);
sprintf('%0.55f',y)
0.3 is not exactly representable in floating point arithmetic, and rounding will not change that fact.
VBBV
2023-6-1
编辑:VBBV
2023-6-2
round function will output the same what we expect based on the number of input decimal precision given to the function. However, sprintf is different thing, which again displays outputs based on the input precision specified in the function
x = 0.3;
sprintf('%0.55f',x)
y = round(x,1)
% round while displaying
sprintf('%0.9f',y)
0.3 is not exactly representable in floating point arithmetic, and rounding will not change that fact.
Then what is the purpose of round function ?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!