2
$\begingroup$

I am well aware of the fact that floating point number have finite precision, so one needs to be careful when comparing them. Still, I find it disturbing/surprising that the following input into Mathematica 9.0.1.0

 In[1]:= f[0.2] = 1;
         f[0.25] = 2;
         f[0.3] = 3;
         f[0.35] = 4;
         f[0.4] = 5;
         f[0.45] = 6;
         f[0.5] = 7;
         Table[f[t], {t, 0.2, 0.5, 0.05}]
         InputForm[%]4

leads to the output

Out[2]:= {1, 2, 3, f[0.35], 5, 6, 7}
         {1, 2, 3, f[0.35000000000000003], 5, 6, 7}

Somehow 0.35 seems to be a different from the other values.

is there a way to define f pointwise to make the above example work as one would naively expect?

$\endgroup$
3
  • 1
    $\begingroup$ Moral lesson: use exact numbers in the left-hand side of piecewise definitions. (I'm pretty sure this is a dupe; I just can't find it.) $\endgroup$ Commented Jun 3, 2015 at 10:00
  • $\begingroup$ Related: (1072), (15907), (47988), (79130) $\endgroup$
    – Mr.Wizard
    Commented Jun 3, 2015 at 18:07
  • $\begingroup$ Proposed duplicate: (51997) $\endgroup$
    – Mr.Wizard
    Commented Jun 3, 2015 at 18:07

1 Answer 1

1
$\begingroup$

One way to guard against this kind of thing is to use an interpolating function:

x = {0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5};
fx = {1, 2, 3, 4, 5, 6, 7};
f = Interpolation[Transpose[{x, fx}]]
Table[f[t], {t, 0.2, 0.5, 0.05}]

{1., 2., 3., 4., 5., 6., 7.}
$\endgroup$

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.