The Cantor function is continuous everywhere and constant almost everywhere, but has an average slope of 1:
The function can be found recursively:
\$f_0(x)=x\$
\$f_{n+1}(x)=\left\{\begin{matrix}\frac{1}{2}f_n(3x)&x\in[0,\frac{1}{3})\\ \frac{1}{2}&x\in[\frac{1}{3},\frac{2}{3})\\ \frac{1}{2}+\frac{1}{2}f_n(3x-2)&x\in[\frac{2}{3},1] \end{matrix}\right.\$
The Cantor function is the limit of this process, \$\lim\limits_{n\to\infty} f_n(x)\$:
The Challenge
Given real x (which can assume the form of a float or rational number) of the interval \$[0,1]\$ and nonnegative integer n, return \$f_n(x)\$.
Rules
This is code-golf so the shortest answer in bytes wins.
Assume only valid input will be given.
Error should be under one ten-thousandth (±0.0001) for the test cases.
Test Cases
In: 0.3 3
Out: 0.3875
In: 0.1 0
Out: 0.1
In: 0.29 4
Out: 0.375
In: 0.11 5
Out: 0.2415625