TP: Implementing the Exponential Function (2/5)

TP: Implementing the Exponential Function (2/5)#

Part 2: Calculating an infinite sum?#

The mathematical definition of the exponential function requires calculating an infinite sum. This

is not possible in practice! We therefore propose to implement the following function which

calculates an approximation of the exponential function obtained by truncating the sum at

a certain rank \(r\): \(e^x \approx \sum_{n=0}^r \frac{x^n}{n!}\)

Copy and paste your puissance and factorielle

functions from part 1 into the two cells below, then complete the implementation of the

expRang function and verify that it passes the provided tests.

### BEGIN SOLUTION
def factorielle(n):
    r = 1
    for i in range(1, n+1):# (int i = 1; i <= n; i++) {
        r = i*r
    return r
### END SOLUTION
### BEGIN SOLUTION
def puissance(x, n):
    r = 1
    for i in range(n):#(int i = 0; i < n; i++) {
        r = r*x
    return r
### END SOLUTION
def expRang(x, r):
    """ Exponentielle tronquée à un certain rang r
      Paramètre x : un nombre à virgule flottante en double précision
      Paramètre r :  un nombre entier positif
      Renvoie 1 + x^1/1!  + x^2/2! + x^3/3! + ...  + x^r/r!
    """
    ### BEGIN SOLUTION
    e = 0
    for i in range(r+1):#(int i=0; i <= r; i++) 
        e += puissance(x,i) / factorielle(i)
    return e
    ### END SOLUTION
expRang(5,1)
6.0
assert( expRang(6, 0) == 1  ) # 6^0/1
assert( expRang(6, 1) == 7  ) # 6^0/1 + 6/1
assert( expRang(6, 2) == 25 ) # 6^0/1 + 6/1 + 36/2
assert( expRang(6, 3) == 61 ) # 6^0/1 + 6/1 + 36/2 + 36*6/6

The higher the rank, the closer we get to the value of \(e^6=403,429\cdots\).

In the cell below, use your expRang function to calculate an

approximation of \(e^{6}\) to the rank \(10\), then **increase the rank until the displayed value

no longer changes** (the added value is too small to change the display).

### BEGIN SOLUTION
expRang(6,24)
### END SOLUTION
403.4287911175401

Now calculate an approximation of the value of \(e^{10}=22026,46\cdots\) with the same order of magnitude:

### BEGIN SOLUTION
expRang(10,22)
### END SOLUTION
22019.951758120904

What do you observe?

BEGIN SOLUTION

The precision is much worse than the example of \(e^6\) despite using the same

rank. The rank required to obtain good precision therefore depends on the real number \(x\) for

which we want to calculate \(e^x\).

END SOLUTION

Increase the rank until the displayed value no longer changes:

### BEGIN SOLUTION
expRang(10, 32)
### END SOLUTION
22026.465632423035

Part 2 Summary#

Congratulations, you have implemented an approximation of the exponential function by truncating its

formula at a certain rank. However, based on the examples above, the user

would like to specify not the rank, but the precision they wish to obtain.

To do this, we must first formalize this idea of precision. This is the subject of

part 3.