2
$\begingroup$

What is the correct method to replace all types of infinity e.g. ComplexInfinity that are present in a Flatten Table format with text that can be recognised by other languages e.g. NaN?

I have // If[ToString[#] == "ComplexInfinity", "NaN", #] & but at present I must apply this separately to every input variable in Table as,

f[x_] := 1/x;
g[x_] := 1/(x - 4);
Table[{f[x] // If[ToString[#] == "ComplexInfinity", "NaN", #] &, 
       g[x] // If[ToString[#] == "ComplexInfinity", "NaN", #] &}, 
      {x, {0, 10, 1}}]
  • Is there a better way to iterate this through the Table?
  • As a side note, if I change, "NaN", #] & to "NaN", N[#, 4]] & to include number formatting then it breaks my code
$\endgroup$
3
  • 4
    $\begingroup$ Something like list /. x_DirectedInfinity :> "NaN"? $\endgroup$ Commented Aug 1, 2016 at 19:26
  • $\begingroup$ @J.M. Works perfectly thanks. w.r.t. previous edit I jsut discovered the GetHelp interface ;) $\endgroup$ Commented Aug 1, 2016 at 19:27
  • $\begingroup$ Instead of searching for them in Google, try this: when you encounter an unfamiliar symbol in your notebook, highlight it and press F1. $\endgroup$ Commented Aug 1, 2016 at 19:30

1 Answer 1

1
$\begingroup$
f[x_] := 1/x;
g[x_] := 1/(x - 4);

list = Quiet @ Table[{f[x], g[x]}, {x, {0, 10, 1}}]

{{ComplexInfinity, -1/4}, {1/10, 1/6}, {1, -1/3}}

Since there isn't only ComplexInfinity, but also other non-numeric forms like Indeterminate and DirectedInfinity, I suggest a more general approach:

Replace[list, x_ /; ! NumericQ[x] :> "NaN", {2}]

{{"NaN", -1/4}, {1/10, 1/6}, {1, -1/3}}

Define it as a function

nan = Replace[#, x_ /; ! NumericQ[x] :> "NaN", {2}] &;

Apply it

nan @ Quiet @ Table[{f[x], g[x]}, {x, {0, 10, 1}}]

{{"NaN", -1/4}, {1/10, 1/6}, {1, -1/3}}

$\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.