Does there exist a continuous function $$f: \mathbb{R} \rightarrow \mathbb{R}$$ that is rational at (Lebesgue) almost every irrational, and irrational at every rational?
Some thoughts: for some $q\in \mathbb{Q}$, $f^{-1}(q)$ is a closed set of positive measure disjoint from the rationals. But of course that's possible. Though it does at least mean that the null set of irrationals where $f$ is irrational is dense in $\mathbb{R}$, by the Baire Category theorem, since the set is the complement of the countable union of nowhere dense sets: $$\big(\mathbb{Q}\cup(\cup_{q\in\mathbb{Q}} f^{-1}(q))\big)^c$$
Also if it exists, $f$ can't be injective on any open interval. So the Cantor function comes to mind, but that obviously doesn't work since it's locally constant on an open set. Maybe a "nowhere injective" function is guaranteed to be locally constant somewhere? I have no idea.
(I saw this asked on reddit, and after thinking for a while I'm too curious not to ask here.)
Best Answer
Such a function exists.
To construct it, we need an auxiliary function $w: \mathbb R \to [0,1]$ that is
This can be obtained from the Cantor function $c: [0,1] \to [0,1]$ by taking some $u \in (0,1)$ for which $c(u)$ is irrational and by assigning $$w(x) = \begin{cases} 0, & x < -u \\ c(x+u), & x \in [-u,0] \\ w(-x), & x > 0 \end{cases}$$ Now we enumerate all rationals as the sequence $\{r_n\}_{n=1}^{\infty}$ and look for the required function $f$ as the sum of the series $$f(x)=\sum_{n=1}^{\infty} \frac {b_n}{2^n}\,w\!\left(\frac{x-r_n}{k_n}\right),$$ where the sequences $\{k_n\}_{n=1}^{\infty} \subset \mathbb R^+$ and $\{b_n\}_{n=1}^{\infty} \subseteq \{0,1\}$ are built inductively.
Let $k_1=1$, $b_1=1$. Then the first term of the series is a continuous function that is rational almost everywhere but is irrational at $x=r_1$.
For any $n>1$, we take $k_n = \displaystyle \min{\left(\frac 1 {2^{n+1}}, \min_{i=1}^{n-1} {|r_i-r_n|}\right)}$ and assign $b_n=0$ if the sum of already defined terms of the series gives an irrational number at $x=r_n$, or $b_n=1$ otherwise. As a result, the $n$th term $f_n(x)=\frac {b_n}{2^n}\,w\!\left(\frac{x-r_n}{k_n}\right)$ so defined is always a continuous function that is rational almost everywhere, has absolute value not greater than $\frac 1 {2^n}$, is nonzero at most at an interval of length $\frac 1 {2^n}$ and changes (or keeps) value of $f(r_n)$ to an irrational number preserving $f(r_i)$ for each $i<n$.
The sum of the series so defined gives us the required function $f$ because: