0

I know diff calculates the discreete derivative, or let's say the difference between consequitive components of a vector.

Not I define a variable

x=-4:1/10:4;
y=diff(diff(x));

Why the heck do I get 1.e-15* and a row of vectors that are non zero? Matlab is being honest by displaying that somehow, in calculating x=-4:1/10:4; it had rounded some digits and though while I execute y=(diff(x)); only and even though it displays all digits same, it some how shows that in it's core they are not stored as same quantities(because it rounded off -4+0.1 or some quantity as other than -3.9 ???). Now, how do I get the standard output? How do I get 0 when it is really zero, like in this case, and non zero whatever it may be like even like 1*e-..., when it is actually non zero?

Note if that is not possible, how do I calculate real/actual diff(x,2), or atleast accurate sign and zero when diff is actually zero? and get the real discreete derivative for functions like cosine instead of some misleading value?

I need to calculate inflection point using diff.

user2178841
  • 849
  • 2
  • 13
  • 26
  • b/c of numerical precision. – Fredrik Mar 17 '13 at 14:38
  • Another victim of floating point inaccuracy. Possible duplicate of [this](http://stackoverflow.com/questions/13699596/is-this-a-matlab-bug-do-you-have-the-same-issue) and [this](http://stackoverflow.com/questions/10930750/matlab-gives-wrong-answer). – Eitan T Mar 17 '13 at 14:44
  • Thanks everyone. I am aware of this numerical precision. I just needed a way to solve this. Thanks Everyone. Just could not spell the exact works. – user2178841 Mar 17 '13 at 16:04

1 Answers1

0

In short, this is because of floating point precision, which is given in MATLAB by eps (i.e, epsilon). Any result you get will be this accurate, not more. Regarding your question, you can prettify the result by rounding all elements or by zeroing almost-zero elements out. For instance, to set all elements small then 10ε to zero:

y = diff(x, 2);
y(abs(y) < 10 * eps) = 0;

For more details, see the answers of the duplicate questions.

Eitan T
  • 32,660
  • 14
  • 72
  • 109