0

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??

  • For instance in the exponential series $e^x=\sum x^k/k!$, you need $n>2|x|$ terms to cover all substantial contributions. After that you can estimate the error by twice the next term. No-one would implement that this way, except as a learning experience. – Lutz Lehmann Aug 23 '23 at 13:08
  • Note that there may be better algorithms than summing Taylor expansions for calculating these functions. For example, the CORDIC algorithm commonly used on systems not designed for numeric processing. Probably that one will not meet your need unless you have some cap on allowable accuracy. But there are other algorithms out there that may prove suitable and faster converging than the Taylor series. – Paul Sinclair Aug 24 '23 at 16:46
  • Thanks @LutzLehmann, thanks @PaulSinclair! – Debtanu Gupta Sep 02 '23 at 07:56

1 Answers1

0

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$.