I want to plot a simple square function wave, like this:

Plot[Table[f[x_] = If[(n - 0.1) <= x <= (n + 0.1), 1, 0], {n, 0, 100, 1}], {x, 0, 10}]

enter image description here

This looks no problem.

But once I extend the x-axis limit to 100, the plot becomes irregular.

Plot[Table[f[x_] = If[(n - 0.1) <= x <= (n + 0.1), 1, 0], {n, 0, 100, 1}], {x, 0, 100}]

enter image description here

I think this is caused by Mathematica not sampling the data points in regular x-spacing.

Is there anyone know how to plot the periodic function correctly, so that it preserves the regularity of the wave shape?

Thank you in advance.

  • $\begingroup$ Increase the PlotPoints setting. $\endgroup$ Apr 19, 2017 at 12:29
  • 1
    $\begingroup$ Also, you should remove the f[x_] = part from the expression, as this will result in unnecessary definitions for f and decrease performance. $\endgroup$
    – Theo Tiger
    Apr 19, 2017 at 12:33
  • $\begingroup$ I have try increasing PlotPoints. It looks better, but it is not sampling with exactly regular [email protected]. $\endgroup$
    – Zhanhao Hu
    Apr 19, 2017 at 12:37
  • $\begingroup$ PlotPoints -> 1000 produces a nice graph. Most of the plotting functions do not do strictly regular sampling. Regular sampling (see MikeY's answer) will miss at least one of the corners at the discontinuities. Is that what you really want. $\endgroup$
    – Michael E2
    May 19, 2017 at 15:50

1 Answer 1


Assuming this is primarily to get a good picture, you can use your knowledge of the function you are plotting and can rig up your own sampling using ListPlot[ ]. First define a better $f[x]$

    f[x_] := If[Abs[Round[x] - x] <= 0.1, 1, 0];

Then you can set a sampling interval $d$ to get the resolution you want...

    ListPlot[Table[{x, f[x]}, {x, 0, 10, d}], Joined -> True]

enter image description here

    ListPlot[Table[{x, f[x]}, {x, 0, 50, d}], Joined -> True]

enter image description here


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.