How to resolve the algorithm Calculating the value of e step by step in the Python programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Calculating the value of e step by step in the Python programming language

Table of Contents

Problem Statement

Calculate the value of   e.

(e   is also known as   Euler's number   and   Napier's constant.)

See details: Calculating the value of e

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Calculating the value of e step by step in the Python programming language

Implementation of Brother's formula:

  • This code computes an approximation of the mathematical constant 'e' using Brother's formula.
  • Brother's formula:
e = 2 + 2 / (2 * 3) + 4 / (2 * 3 * 4) + 8 / (2 * 3 * 4 * 5) + ...
  • The code starts with the initial value of 'e' as 0 and sets 'e0' to 2 (the first term of the series).
  • It iterates until the difference between 'e' and 'e0' becomes less than a very small value (1e-15).
  • In each iteration, it updates 'e0' with the current value of 'e', increments 'n' (which represents the current term in the series), and calculates the next term in the series using a factorial function 'fact'.
  • Finally, it prints the computed value of 'e', the real value of 'e' (from 'math.e'), the error between the computed and real values, and the number of iterations performed.

Approximation of 'e' using a large factorial:

  • This code uses a large factorial value (10^1000) to approximate 'e'.
  • It initially sets 'e' and 'rfct' (running factorial) to this large value.
  • It iterates until 'rfct' becomes 0, dividing 'rfct' by 'n' in each iteration to get the next factorial value.
  • The value of 'e' is updated by adding 'rfct' in each iteration.
  • Finally, it prints the computed 'e' and the number of steps taken.

Approximation of 'e' using 'itertools.accumulate' and 'functools.reduce':

  • This code uses 'itertools.accumulate' and 'functools.reduce' to calculate an approximation of 'e'.
  • The 'eApprox' function uses 'reduce' to compute the sum of the series 1 + 1/1 + 1/2 + 1/3 + ... + 1/17.
  • The 'scanl' function is used to generate a list of intermediate values while computing the sum.
  • Finally, it prints the computed 'e' value.

Approximation of 'e' using 'functools.reduce':

  • This code uses 'functools.reduce' to compute an approximation of 'e' up to a specified number of iterations.
  • The 'eApprox' function takes an integer 'n' and computes the sum of the series 1 + 1/1 * 1! + 1/2 * 2! + 1/3 * 3! + ... + 1/n * n!.
  • The 'go' function is used as the reduction function, updating the current 'e' value and the factorial denominator in each iteration.
  • Finally, it prints the computed 'e' value.

Source code in the python programming language

import math
#Implementation of Brother's formula
e0 = 0
e = 2
n = 0
fact = 1
while(e-e0 > 1e-15):
	e0 = e
	n += 1
	fact *= 2*n*(2*n+1)
	e += (2.*n+2)/fact

print "Computed e = "+str(e)
print "Real e = "+str(math.e)
print "Error = "+str(math.e-e)
print "Number of iterations = "+str(n)


e = rfct = 10 ** 1000
n = 1
while rfct:
    n += 1
    e += rfct
    rfct //= n
print(f"{e}\n...in {n} steps")


'''Calculating an approximate value for e'''

from itertools import (accumulate, chain)
from functools import (reduce)
from operator import (mul)


# eApprox :: () -> Float
def eApprox():
    '''Approximation to the value of e.'''
    return reduce(
        lambda a, x: a + 1 / x,
        scanl(mul)(1)(
            range(1, 18)
        ),
        0
    )


# TEST ----------------------------------------------------
# main :: IO ()
def main():
    '''Test'''

    print(
        eApprox()
    )


# GENERIC ABSTRACTIONS ------------------------------------

# scanl is like reduce, but returns a succession of
# intermediate values, building from the left.
# See, for example, under `scan` in the Lists chapter of
# the language-independent Bird & Wadler 1988.

# scanl :: (b -> a -> b) -> b -> [a] -> [b]
def scanl(f):
    '''scanl is like reduce, but returns a succession of
       intermediate values, building from the left.'''
    return lambda a: lambda xs: (
        accumulate(chain([a], xs), f)
    )


# MAIN ---
if __name__ == '__main__':
    main()


'''Approximation of E'''

from functools import reduce


# eApprox :: Int -> Float
def eApprox(n):
    '''Approximation of E obtained after N iterations.
    '''
    def go(efl, x):
        e, fl = efl
        flx = fl * x
        return e + 1 / flx, flx

    return reduce(
        go,
        range(1, 1 + n),
        (1, 1)
    )[0]


# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''Approximation of E obtained after 20 iterations.'''

    print(eApprox(20))


# MAIN ---
if __name__ == '__main__':
    main()


  

You may also check:How to resolve the algorithm Sorting algorithms/Counting sort step by step in the Pascal programming language
You may also check:How to resolve the algorithm Count the coins step by step in the Commodore BASIC programming language
You may also check:How to resolve the algorithm Hello world/Web server step by step in the Genie programming language
You may also check:How to resolve the algorithm Singleton step by step in the PHP programming language
You may also check:How to resolve the algorithm Take notes on the command line step by step in the PowerShell programming language