Message Boards Message Boards

0
|
6690 Views
|
2 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Why does Piecewise yield empty plot when function definition seems okay?

Posted 10 years ago

I am using Piecewise with conditions based on whether x is a rational number or not. The function assignment seems to work. But when I plot it, an empty plot shows up (though the PlotLabel looks nice).

Clear[f]; 
f[x_] := Piecewise[{{x, 
    Element[x, Rationals]}, {-x, ! Element[x, Rationals]}}]; Plot[
 f[x], {x, -5, 5}, 
 PlotLabel -> "f(x)=" <> ToString[TraditionalForm[f[x]]]]

What's wrong? I tried using different options with PlotRange and Mesh, thinking that I Plot needed to sample some x values that fell into the rational category. No luck yet.

Here is another example with the same result: an empty plot but the function assignment works.

Clear[f]; 
f[x_] := Piecewise[{{1, Element[x, Integers]}, {0, 
    Element[x, Reals]}}]; Plot[f[x], {x, -3, 3}, 
 PlotLabel -> "f(x)=" <> ToString[TraditionalForm[f[x]]]]

Any insight is much appreciated!

POSTED BY: Glen Deering
2 Replies
Posted 10 years ago
POSTED BY: Glen Deering

Element[Rationals] does not return True or False for real values. For example

enter image description here

So your function was returning unevaluated for all the values between -5 and 5, since Plot was using real values for x in its sampling.

data = Table[{i, f[i]}, {i, -5, 5, .1}]

enter image description here

And plot did not know how to plot the above.

You can always check the function using a Table command, such as

    data = Table[{i, f[i]}, {i, -5, 5, .1}]

To see what values it generates.

POSTED BY: Nasser M. Abbasi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract