problem with checking equality of successive x-intervals

i am writing a function to approximate area under a line using a series of x-y points that are not always evenly spaced apart. depending on how many successive x-intervals of equal size I have, my function will use the best approximation out of the simpsons 1/3, simpsons 3/8 or simply the trapezoidal rule.
now the question:
the problem is that for successive intervals which I know are equal, the logic check of
if x(i + 1) - x(i) ~= x(i + 2) - x(i+1)
is coming out as true, which I am pretty sure is simply do to the use of floating point numbers. I have changed it to check if the difference between 2 successive intervals is >1e-6 instead of checking if they are not equal, but my question is if there is another way to do it that is more precise. my function does work ok since I made it a tolerance instead of an inequality, but I might prefer some other method if there is one available.
thanks

Answers (1)

The comparison as implemented is the only way to avoid exact comparison in floating point as you've surmised. At least thru R2012b TMW hadn't implemented any "fuzzy" comparison operators other than perhaps in some toolboxes; whether there's something later or not I haven't checked. Seems like a likely candidate for some submission from File Exchange but I haven't done a search there, either.
The one thing I'll note in writing a comparison such as this where you've used a fixed interval is that you can make it more general by use of the function eps as applied to the values you're comparing to get a range of magnitudes that are in the ballpark of precision of the values themselves. Something like
abs(diff(x))<3*eps(mean(x)
will be a difference of 3 LSBs in the range of the average of x.
Another alternative is to use a percentage or fraction of the value in a similar manner -- that could be easier to select for a specific application, perhaps.

Categories

Find more on Mathematics in Help Center and File Exchange

Asked:

on 21 Apr 2015

Answered:

dpb
on 21 Apr 2015

Community Treasure Hunt

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

Start Hunting!