1
$\begingroup$

I am attempting to use Table to evaluate a function at specific values. The function is first defined.

f[x_, y_] := ArcTan[x/y];

The known definitions are applied

f[x_, 0] = 1;

?f
Global`f
f[x_,0]=1

f[x_,y_]=ArcTan[x/y]

And the function is tested

f[x, 0]

1

Using replacement

f[x, y] /. y -> 0

Power::infy: Infinite expression 1/0 encountered.

Indeterminate

Using lists

Table[f[x, y], {y, -1, 1, 0.5}]

Power::infy: Infinite expression 1/0. encountered.

{-ArcTan[1. x], -ArcTan[2. x], Indeterminate, ArcTan[2. x], 
 ArcTan[1. x]}

Interestingly enough, this seems to only fail when the list steps are fractional

Table[f[x, y], {y, -1, 1, 1}]

{-ArcTan[x], 1, ArcTan[x]}

Why is the known value of the function not being used to provide a solution is these specific instances?

Note that whether the definition is delayed or not does not have an effect on this behavior.

$\endgroup$
  • $\begingroup$ try Hold[f[x, y]] /. y -> 0 // ReleaseHold or Unevaluated[f[x, y]] /. y -> 0 // Evaluate? $\endgroup$ – kglr Apr 8 at 17:25
  • $\begingroup$ and try Trace[f[x, y] /. y -> 0] // Column to see what is happening. $\endgroup$ – kglr Apr 8 at 17:26
  • $\begingroup$ In your first Table example, it fails because it's using machine precision numbers due to the 0.5. Either change it to {y, -1, 1, 1/2} to make them exact numbers, or add f[x_, 0.] = 1 somewhere to tell it that it should treat a machine precision zero in the same way as exact zero. $\endgroup$ – MassDefect Apr 8 at 17:32
  • $\begingroup$ Beautiful, thank you both. I'll do some reading on Mathematica's handling of numerical precision. $\endgroup$ – epsilon0 Apr 8 at 17:52
4
$\begingroup$

f[x,y] is evaluated to ArcTan[x/y] before ReplaceAll gets to work. This is because ReplaceAll has a low precedence:

Precedence /@ {f[x, y], ReplaceAll}
{1000., 110.}

You can prevent evaluation of f[x,y] before replacement of y with 0 using any of the following

Unevaluated[f[x, y]] /. y -> 0 // Evaluate
Hold[f[x, y]] /. y -> 0 // ReleaseHold
Inactive[f][x, y] /. y -> 0 // Activate
Inactivate[f[x, y], f] /. y -> 0 // Activate

all give 1.

Use Trace to see the source of error:

Trace[f[x, y] /. y -> 0] // Column

enter image description here

Pre-mature evaluation does not happen in Table example (because Table has attribute HoldAll). As noted by MassDefect in comments, you need to modify the definition of f to specify both f[x_,0] and f[x_,0.] are 1 to avoid the error message:

f[x_, y_] := ArcTan[x/y];
f[x_, 0 | 0.] = 1;
Table[f[x, y], {y, -1, 1, .5}]
  {-ArcTan[1. x], -ArcTan[2. x], 1, ArcTan[2. x], ArcTan[1. x]}
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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