Euler Transform on Leibniz Series of Pi So i read about simple series for Pi named Leibniz Series for Pi. Here is its Link:-
Series . I made a program for it and soon realised that it converges very slows . So i did Euler accelerate for Alternating Series https://en.wikipedia.org/wiki/Series_acceleration#Euler's_transform and made this recursive program:-
import functools
import decimal
def LebniezTerm(n):
  return 1/(2*n + 1)

@functools.lru_cache(maxsize = 12800) 
def ndiffrence(n,depth):
  if depth == 0:
    return LebniezTerm(n)
  a = ndiffrence(n,depth-1)
  b = ndiffrence(n+1,depth-1)
  return (a - b)

def EulerAccelerate(n):
  i = decimal.Decimal(1)
  pi = decimal.Decimal(0)
  while (i &lt;= n):
    pi = pi + decimal.Decimal(ndiffrence(0,i-1))/decimal.Decimal(2**i) 
    i+=1
  return pi

4*EulerAccelerate(600)

Here i did and optimisation using Functools but it is still slow. So can it become more optimised ?
How can the accuracy get more increased ?
What I found out by simply taking the time the calculation takes, is that casting to Decimal is a very costly operation. Dropping that in certain places (see my code) brings down the overall runtime to ~ 30-40%.
Besides, the Leibnitz terms can easily be precomputed (another Best Practice of optimization) as the list will be comparatively short. Surprisingly, this does not save much.
Using a module method with a local name save some time as well (import xxx from this_module as local_name instead of using this_module.xxx multiple times).
In EulerAccelerate(), the loop variable i does not need to be of type Decimal which saves a lot. Replacing 2**(i+1) with a simple addition yields another (small) saving.
Stepping back from the code analysis, I think changing the algorithm from recursive to iterative would speed up the calculation a lot, much more than those micro-optimizations.
results on my notebook: maxdepth=24, accurate to 8 places: pi=3.1415926, runtime=10 s
    import functools
    from decimal import Decimal
    import time

    ## @functools.lru_cache(maxsize = 12800)
    def ndifference(n, depth):
        if depth == 0:
            return LT[n]  #   = 1.0/(2*n + 1)
        a = ndifference(n, depth-1)
        b = ndifference(n+1, depth-1)
        return (a - b)

    def EulerAccelerate(n):
        pi = 0
        ith_power_of_2 = 2                # 2**(i+1)
        for i in range(n):
            pi += Decimal(ndifference(0, i)) / ith_power_of_2
            ith_power_of_2 += ith_power_of_2
        return pi


    # ---------------------------------
    maxdepth = 24
    # create Leibnitz terms beforehand; LT is global
    LT = [(1.0/(2.0*i+1.0)) for i in range(maxdepth+1)]

    t = time.time()
    print 4 * EulerAccelerate(maxdepth)
    print time.time()-t