MatLab-比较两个浮点数时如何接受公差 [英] MatLab - How to accept a tolerance when comparing two float numbers
问题描述
我正在尝试使用数字方法中的复合梯形规则制作一个函数来计算积分.但问题是,当我要检查输入数据点是否均匀分布时,出现了错误.因为有浮点数.这是我的代码
I'm trying to make a function to compute an integral using Composite trapezoidal rule in numerical methods. But the thing is, when I'm going to check whether the input data points are equally spaced, There is a error. Because of the floating point numbers. Here's my code
function answer = composite_trapezoidal (X, Y)
lx = length(X);
ly = length(Y);
h = X(2) - X(1);
validity = 1;
series_sum = 0;
answer = 0;
if (lx ~= ly)
fprintf('Error ! Dimensions Of Data Point Vectors Doesn''t Match\n');
else
for i = 1:lx - 1
hTmp = X(i + 1) - X(i);
if (hTmp ~= h)
validity = 0;
fprintf('Invalid Data Points. Data Must Be Equally Spaced !\n');
break;
end
end
end
if (validity == 1)
for i = 2:lx - 1
series_sum = series_sum + Y(i);
end
answer = (h / 2) * (2 * series_sum + Y(1) + Y(ly));
end
考虑输入 x = linspace(0,2,7);
然后该函数以数据点不等距"终止.但事实是它们是使用linspace计算的.我能理解这个问题.点是0、0.3333333、0.6666667等.因此,在四舍五入时它们的间距不相等.但是问题是我们可以解决这个问题吗?
consider the input x = linspace(0, 2, 7);
Then the function terminates with "data points are not equally spaced". But the thing is they were computed using linspace.
I can understand the problem. Points are 0, 0.3333333, 0.6666667, etc. So they aren't equally spaced when rounding up. But the problem is Can we fix this ?
推荐答案
使用舍入数字检查相等性通常是不稳定的.您可以尝试使用可接受的公差,例如abs(hTmp-h)<10 ^ -4甚至更好使用abs(hTmp-h)/abs(hTmp)<10 ^ -2
Checking equality with rounded numbers is usually unstable. You could try using an acceptable tolerance such as abs(hTmp-h)< 10^-4 or even better use a relative tolerance with abs(hTmp-h)/abs(hTmp) < 10^-2
这篇关于MatLab-比较两个浮点数时如何接受公差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!