TITLE: Smooth functions for which $f(x)$ is rational if and only if $x$ is rational
QUESTION [43 upvotes]: A friend of mine introduced me to the following question: Does there exist a smooth function $f: \mathbb{R} \to \mathbb{R}$, ($f \in C^\infty$), such that $f$ maps rationals to rationals and irrationals to irrationals and is nonlinear?
I posed this question earlier in math.stackexchange.com (link to the question) where it received considerable interest. There hasn't been an answer so far, but one commenter suggested to bring it here.
Related results

The friend who told me the problem
has been able to prove that no
polynomial satisfies the required
conditions.
If we required just that $f \in C^1$, then we can cut and paste the function
$x \mapsto \frac{1}{x}$ to provide a nonlinear example:
$$f(x) = \begin{cases}\frac{1}{x-1} + 1, & x \le 0 \\\\ \frac{1}{x+1} - 1, & x \ge 0\end{cases}$$

REPLY [35 votes]: There are such functions. Moreover any diffeomorphism $f_0:\mathbb R\to\mathbb R$ can be approximated by such $f$. For the sake of simplicity I assume that $f_0'\ge 2$ everywhere.
Enumerate the rationals: $\mathbb Q=\{r_1,r_2,\dots\}$, and construct a sequence $f_0,f_1,f_2,\dots$ of self-diffeomorphisms of $\mathbb R$ satisfying the following:

$f_{2k-1}(r_k)\in\mathbb Q$, and $f_n(r_k)$ is the same for all $n\ge 2k-1$
$f_{2k}^{-1}(r_k)\in\mathbb Q$, and $f_n^{-1}(r_k)$ is the same for all $n\ge 2k$.
The first $k$ derivatives of the difference $f_k-f_{k-1}$ are bounded by $2^{-k}$ everywhere on $\mathbb R$.

Such a sequence has a limit $f$ in $C^\infty$, and this limit is a diffeomorphism satisfying $f(\mathbb Q)\subset\mathbb Q$ and $f^{-1}(\mathbb Q)\subset\mathbb Q$.
The sequence $\{f_i\}$ can be constructed by induction. To construct $f_{2k-1}$ from $g:=f_{2k-2}$, consider $g(r_k)$. If it is rational, let $f_{2k-1}=g$. If not, let $I$ be an open interval containing $r_k$ and not containing any of the points $r_i$ and $g^{-1}(r_i)$ for $i\le k-1$. (Note that $r_k$ is different from these points due to the fact that $g(r_k)\notin\mathbb Q$). Then define $f_{2k-1}=g+\varepsilon\cdot h$ where $h$ is your favorite smooth function with support contained in $I$ and such that $h(r_k)\ne 0$,
$\varepsilon$ is so small that the above derivative estimates hold and is chosen so that $f_{2k-1}(r_k)\in\mathbb Q$. To construct $f_{2k}$ from $f_{2k-1}$, do a similar perturbation near the pre-image of $r_k$, assuming it is not yet rational.