Can piecewise defined functions always be differentiated piece by piece?

Guess you have a function $f(x) : \mathbb{R} \rightarrow \mathbb{R}$ (or a subset of $\mathbb{R}$) with $f (x) := \begin{cases} x^3 & \text{if } x \geq 0 \\ x^2 & \text{otherwise} \end{cases}$.

The derivative $f': \mathbb{R} \rightarrow \mathbb{R}$ of $f(x)$ is $f' (x) := \begin{cases} 3 \cdot x^2 & \text{if } x \geq 0 \\ 2 \cdot x & \text{otherwise} \end{cases}$.

To get this derivate I could simply differentiate the first part and the second part.

Can you calculate the derivate of every piecewise defined function this way?

I recently saw Thomae's function:

$f(x)=\begin{cases} \frac{1}{q} &\text{ if } x=\frac{p}{q}\mbox{ is a rational number}\\ 0 &\text{ if } x \mbox{ is irrational}. \end{cases}$

I thought there might be a differentiable function which is defined like that and which can't be derived simply by deriving it piece by piece.

-
How would you find the derivative on a "piece" that contains no open intervals? – David Mitra Mar 19 '12 at 16:20
As the others pointed out, it depends on your definition of "piecewise defined functions", but remember that differentiating is a local process: if your pieces are connected and contain nonempty open intervals, you would differentiate piece by piece, but you still have to be careful with the endpoints. – M Turgeon Mar 19 '12 at 17:58

The derivative of your $f(x)$ is automatically $3x^2$ only for $x>0$. It happens to have derivative $0$ at $x=0$, but that's "because" the derivative of $x^2$ happens to be $0$ at $x=0$. If we replace $x^2$ by $x$, then the derivative will not exist at $x=0$.

The Thomae function is not ordinarily considered to be piecewise defined.

-
If it is not ordinarily considered to be piecewise defined, how would you call it? – Martin Thoma Mar 21 '12 at 16:11
@moose: I do not think there is a special name for this kind of definition. But "piecewise" means that the pieces are piece-like, meaning intervals. – André Nicolas Mar 21 '12 at 16:15

If the pieces are required to be over connected non-trivial intervals, then that would be how you do that, except at the endpoints where the pieces meet up. At the endpoints you have to check for the left derivative and right derivative to make sure they are equal. If you do not require intervals then

$$f(x)= \begin{cases} 4 & \text{if x=2}\\ \frac{x^2-4}{x-2} & \text{if x\neq 2} \end{cases}$$

is an example where you would not just differentiate $4$ to get $0$.

-