0

I apply the following command:

Do[Print[var[u] = u], {u, -1, 1, 0.1}]

It produces out put. But when i recall the value var[-0.4] as below:

In[2]:= var[-0.4]

Out[2]= var[-0.4]

It produces var[-0.4] instead of the value. It can be handled if i replace step size 0.1 by 1/10 but i want to work with decimal point form. It may be due to floating point. If any one may help to give a good suggestion on it. It will be highluy appreciated.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
Usman
  • 157
  • 7
  • 1
    Use exact numbers and add a definition to var to handle inexact numbers: Do[var[u] = u, {u, -1, 1, 1/10}]; var[r_Real] := var[Rationalize[r]] – Mr.Wizard Dec 21 '16 at 04:26

1 Answers1

2

It is a precision issue

Clear[var]

Do[var[u] = u, {u, -1, 1, 0.1}]

DownValues[var][[15]]//FullForm

(*  RuleDelayed[HoldPattern[var[0.40000000000000013`]], 0.40000000000000013`]  *)

Consequently, you would need to enter

var[0.40000000000000013]

(*  0.4  *)

%//InputForm

(*  0.40000000000000013  *)

To avoid the precision issue, use exact numbers

Clear[var]

Do[var[u] = u,{u, -1, 1, 1/10}]

Then

var[4/10] == var[2/5] == 2/5

(*  True  *)
Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198