TransWikia.com

Putting "forbidden values" for functions

Mathematica Asked on December 5, 2020

I am defining a function $f(x)$ and I would like to put undefined values to some $x$. The point is that if I plot the function I don’t want an error to be returned, I want that for all the plotting function I will use, it will "ignore" the $x$ corresponding to forbidden values.

Is there a simple way to do this (i.e not writing 50 lines of functions). Is there a simple keyword for that ?

2 Answers

I thought that Plot ignored values that are not numbers and also suppressed errors. When I try the following:

f[x_?(2 <= # <= 4 &)] := 1/0;
f[x_?(4 < # <= 6 &)] := Indeterminate;
f[x_] := x^2;

and then

Plot[f[x],{x,0,10}]

I don't get any errors and the plot ignores x values from 2 to 6.

Correct answer by OutsideLoop on December 5, 2020

There are two issues here:

Defining the function

You could use a Condition to prevent the function from evaluating at the forbidden points:

forbiddenValues = {1, E, Pi};
forbiddenQ[x_] := Or @@ Table[x == value, {value, forbiddenValues}] // Evaluate;
f[x_] /; !forbiddenQ[x] := x^2
f /@ {1, 2, E, 4, Pi}
(* {f[1], 4, f[E], 16, f[Pi]} *)

Plotting

From @Natas's comment, use Exclusions:

Plot[f[x], {x, 0, 5}
  , Exclusions -> forbiddenValues
  , ExclusionsStyle -> {None, Directive[Red, PointSize[Large]]}
]

Plot with exclusions

Despite the definition above, you still need to explicitly specify the locations of the exclusions because they do not get detected automatically. Therefore, if the only goal is to generate a plot with the exclusions, I would not bother with defining the function above. Just plot x^2 and use the appropriate exclusion options.

Answered by yawnoc on December 5, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP