# Algorithm to approximate decimal expansion for fraction

Let's say I have some fraction $$\frac{n}{m}$$, which is fully reduced. how can I approximate its decimal expansion to a given accuracy?

Like $$\frac{1}{7}$$ is 0.143 if you want 3 decimal places of accuracy but 0.14285714 if you want 8 decimal places of accuracy.

Currently I use the following algorithm

Let be $$a \in \{1,2,\ldots\}$$ a specifier for accuracy.

Calculate: \begin{align} p &= \lceil \log_{10}(m) \rceil + a \\\\ f &= \lfloor \frac{10^p}{m} \rfloor \\\\ v &= n \cdot f \end{align} Then in $$v$$ insert the decimal comma at the correct place or add 0. with leading zeros.

Is this a good algorithm or are there improvements I could do?

• This is a fairly good algorithm, but you may want to change the 10 to 2... That is, $p = \lceil \log_2{(m)} \rceil + a$, and $f = \lfloor \frac{2^p}{m} \rfloor$. According to en.wikipedia.org/wiki/… the Newton-Raphson division will divide numbers in the time it takes to multiply, so this would be better for larger numbers. Also, you could try asking this question on Computer Science Stack Exchange or CSTheory Stack Exchange. Apr 24, 2020 at 9:59
• @MattGroff I dont see why choosing $2$ as a base would improve it? Because what I'm basicly doing is searching for $f$ so that $\min(\left| 10^p - f \cdot m\right| )$ is close to $0$. So in words I search for a factor that brings $m$ the closest to some power of $10$. Apr 24, 2020 at 10:10
• I believe that in practice, $2^p$ is used so that the computer can do a simple bit shift, instead of actually taking $2$ to the $p$th power. That's why I said that. Apr 24, 2020 at 10:13