I need to define a function that depends on a variable taking values on discrete values, for example:

xi = 0.04;
xf = 0.5;
dx = 0.001;
Table[f[x] = x^2, {x, xi, xf, dx}];

Next, I wish to take, for example, its second derivative.

secondder=Table[{x, (f[x - dx] - 2*f[x] + f[x + dx])/dx^2}, {x, xi + dx,xf - dx, dx}];

The problem is that when Mathematica is computing the increments, it adds precision, that is:

xi + dx + dx + dx



so it doesn't return the value of f[0.043] previously defined. I have tried SetPrecicion, SetAccuracy, but I can't make it work.

Thanks for any help!


1 Answer 1

  • You could use arbitrary precision definitions for your values: xi = 1/25; xf = 1/2; dx = 1/1000;, with the rest of the code unchanged.

  • Alternatively, you could call f[Round[x - dx, dx]] instead of f[x - dx] in your calculation of the derivative:

    secondder =
        {x, (f[Round[x - dx, dx]] - 2*f[x] + f[x + dx])/dx^2},
        {x, xi + dx, xf - dx, dx}
  • You can achieve the same result using:

    table = Table[x^2, {x, xi, xf, dx}];
      Range[xi + dx, xf - dx, dx],
    (* Out: {{0.041, 2.}, {0.042, 2.}, ...., {0.498, 2.}, {0.499, 2.}} *)
  • I am not sure why you couldn't define Clear[f]; f[x_] := x^2 instead. Even if you are calculating the derivative numerically, you should always be able to calculate the function's value for any value of the independent variable...

  • $\begingroup$ thanks for your reply! This was just a simple example, my 'f' doesn't have a closed form, I evaluate it numerically. Unfortunately neither the Round or Difference solution seem to work: if you evaluate it you will see that things like 0.043000000000000003` remain. But I liked the Round solution and I am trying to make it work. $\endgroup$
    – aprendiz
    Dec 10, 2020 at 20:33
  • $\begingroup$ I forgot to say: using arbitrary precision xi = 1/25; xf = 1/2; dx = 1/1000 is not an option because I have to storage a large ammount of data. I am puzzled by this! Table[FullForm[Round[x - dx, dx]], {x, xi + dx, xf - dx, dx}] $\endgroup$
    – aprendiz
    Dec 10, 2020 at 20:42
  • $\begingroup$ @aprendiz the .00000000003 stuff are due to representing machine-precision decimals in binary form. They won't really "go away" as long as you are using machine-precision. Also, could you say again why the Differences approach won't work for you to continue further? $\endgroup$
    – MarcoB
    Dec 11, 2020 at 1:08
  • $\begingroup$ I was wrong, the Differences approach does work, thank you! $\endgroup$
    – aprendiz
    Dec 11, 2020 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.