Periodic piecewise function

I have some very simple questions about how to define a periodic function in Mathematica. I’ve never used Mathematica before so please forgive my ignorance.
What I need to do is graph and obtain the Fourier series for a 2*Pi-periodic function. My function is defined as follows:

  • exp(x) when -pi < x < pi
  • cosh(pi) when x = -pi or x = pi

I told this to Mathematica this way:

f[x_] := Piecewise[{{Exp[x], -Pi < x < Pi}, {Cosh[x], 

    x == -Pi || x == Pi}}]

I think it worked properly because when I evaluate the function I get the appropriate results.

Now the problem is I need to extend this definition to the whole real number line, taking into account that f(x+2pi) = f(x). I tried to do this several ways, but none of them worked and I couldn’t figure out a solution.

Another issue is how to plot this showing the points (n*pi, cosh(n*pi)). When I plot the function it shows the line for exp(x) but nothing for cosh(x), and I need the dots to be seen. Any help would be appreciated.

Would defining your function as

Exp@Mod[x, 2 Pi, -Pi]

work for your purposes? It will work for plotting (except for the Cosh part, but that value is taken only in separate points).

For the periodic continuation, could try g := f[Mod[x, 2 Pi, -Pi]] and use Epilog to add the discrete points to the plot.

EDIT: Too slow, Szabolcs already answered :slight_smile:

Another way is thinking recursively!

f[x_] := Which[x > Pi, f[x - 2*Pi],
               x < -Pi, f[x + 2*Pi],
              -Pi < x < Pi, Exp[x],
               x == -Pi || x == Pi, Cosh[x]
  ]

All the solutions worked like a charm, just like I wanted. Thank you very much!