Humor can be defined in terms of information theory. Basically, humor is defined as inversion. So when telling a joke, there is a buildup to a punchline. This buildup can be positive (i.e. we are saying good and/or happy things), or negative (we are saying horrible things). At the point of the punchline, the joke inverts. It is this sudden inversion that makes us laugh.
So if we were building up to a good place, the punchline tells us that we were really building up to an evil place. Likewise, if we were building up to a nominally evil place, the punchline inverts us to a good place. It actually doesn't matter which direction we start in or end up, either way we laugh when we get the joke.
In words, we consider emotional intensity \(E\) as a function of time: \(E = f(t)\). This function is exponential, i.e.
\begin{align} E & = k e^t \\ \end{align}
We can use any base for the exponent, but here since we are speaking mathematically we use the natural base \(e\). If we were implementing this in code, we would probably use a base of 2.
If the buildup is positive then \(k\) is positive, e.g. \(k = 1\). If the buildup is negative, then k is negative, e.g. \(k = -1\). The rhythm and volume of the buildup determines the magnitude of \(k\); a really loud happy buildup might have \(k = 8\), while a soft sad buildup might have \(k = -1/2\).
At the point of punchline (\(t = p\)), the function experiences a discontinuity and inverts itself. So if \(k = 1\) before the punchline, \(k = -1\) after the punchline, and vice versa. Mathematically:
\begin{align} \left\{% \begin{array}{l} \forall t < p; E = k e^t \\ \forall t >= p; E = -k e^t \\ \end{array}% \right. \end{align}This can be expressed in the form of a graph like this: