How many terms I need to take to calculate the value of $ \ln(x) $ or $ e^x $ accurately up to $ n $ decimal places?

77 Views Asked by At

I'm making my own RealNumber class in Python. All four fundamental operations - Addition, Subtraction, Multiplication and Division are defined there. In case of division, user can specify up to how many digit he/she wants to calculate after the decimal place, if the Quotient is not finite.

Now, I want to define the pow() function. Suppose, I need to calculate $ a ^ b $, where $ a, b \in\mathbb{R} $.

I want to do the operation as

Let, $ y = a^b $

$ ⇒ y = e^{\ln(a^b)} $

$ ⇒ y = e^{b*\ln(a)} $

First I need to calculate the $ \ln(a) $ using Logarithm series, next I need to use the $ e^x $ series to calculate $ e^{b*\ln(a)} $.

Now, the question is, as this is my custom class, I want to specify that how many digits I want accurately after the decimal point in the final result.

Suppose, I want $n$ digits accurately after the decimal point. To do that, how many terms I need to take for those two series??

1

There are 1 best solutions below

3
On BEST ANSWER

Take the case of the exponential function and write it as

$$e^x=\sum_{n=0}^p \frac {x^n}{n!}+\sum_{n=p+1}^\infty \frac {x^n}{n!}$$

and, as @Lutz Lehmann clearly commented and explain, you want to know $p$ such that

$$2 \frac {x^{p+1}}{(p+1)!} \leq 10^{-k}$$ tat is to say $$(p+1)! \geq 2 x^{p+1}\,10^k$$

If you look at @robjohn's answer to this old question of mine, you will find a superb approximation.

Adapted to this case, the result will be $$\color{blue}{p=\left\lceil e\,x \exp\Bigg(W\left(\frac{(k+\log (2))\log (10) }{e x}-\frac{\log (2 \pi x)}{2 e x}\right) \Bigg)-\frac 3 2\right\rceil}$$where $W(.)$ is Lambert function.

Let me try for $x=\pi$ and $k=50$; this gives $p=58$.

Checking $$2 \frac {\pi ^{57}} {(57+1)!}=1.85\times 10^{-50}\quad\quad\quad 2 \frac {\pi ^{58}} {(58+1)!}=9.86\times 10^{-52}$$

$$e^\pi-\sum_{n=0}^{57} \frac {x^n}{n!}=3.07\times 10^{-50}\quad\quad e^\pi-\sum_{n=0}^{58} \frac {x^n}{n!}=1.63\times 10^{-51}$$

To give you an idea of the accuracy, before ceiling, the value is $57.9081$ while the exact solution is $57.6010$.