Message Boards Message Boards

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

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

Posted 9 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 9 years ago

Thanks for the tip on using Table. It seems that Plot uses only Reals when generating data for the graph. And that seems especially true when one explicitly sets the increment value to .1. I considered this when the plot came up empty. But I didn't know how to tell Mathematica to look for all possible Rationals in this domain--there are bound to be an infinite number as well as an infinite number of non-rationals. (This is part of a textbook problem from an old Calculus book. I wonder what "they" expected the student to come up with.)

As you have kindly pointed out (here, and in an earlier response to my post that you must have edited out), I have misused Element. (I'm still struggling to grasp how to implement conditionals versus assertions.) Thanks for any help my understanding.

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