Error-check spacing of a vector

1 回表示 (過去 30 日間)
Zheng Sen Ter
Zheng Sen Ter 2021 年 9 月 29 日
コメント済み: Zheng Sen Ter 2021 年 9 月 29 日
Hi, I encountered a problem doing integration using simpson 3/8 or 1/3 or trapezoid rule on 2 sets of vectors x and y. It turns out that the error occur in my function file. For integration, i need to check the spacing of vector x to be the same first.
let me put it like this example:
range = [10,20];
p = 1e-3;
x = range(1):p:range(2);
% check spacing
n = length(x)
h = x(2)-x(1)
for i = 2:n-1
if x(i+1) - x(i) ~= h
error('x spacing not correct')
end
end
Although each spacing of x should be the same, which is p=1e-3. However, the for loop gives error. (error: x spacing ot correct) . It doesnt give error if p = 1.
Is this because of the limitation of Matlab? Sorry if this is a pretty basic theory i should know.
Thanks for your help.

採用された回答

Geoff Hayes
Geoff Hayes 2021 年 9 月 29 日
Zheng - you are trying to compare two floating point numbers using (in this case) the inequality operand. When comparing two floats or doubles, you need to use a tolerance as described at Compare floating-point numbers as the equality (or inequality) operands will not necessarily give the desired result.
  1 件のコメント
Zheng Sen Ter
Zheng Sen Ter 2021 年 9 月 29 日
Got it. Thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMathematics and Optimization についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by