Use python to calculate a special limit

11,445

Solution 1

The calculation of limits is not implemented in python by default, for this you could use sympy

from sympy import *

x= symbols('x')
r = limit((1+1/x)**x, x, oo)
print(r)

Output:

E

Solution 2

Because you are esssentially performing two separate limits:

lim x->infty ((lim y->infty (1 + 1/y))^x)

which Python correctly evaluates as 1.

Here is a poor-man's-implementation of the proper limit:

def euler(x):
    return (1+1/x)**x

for i in range(10):
    print(euler(10**i))

2.0
2.5937424601000023
2.7048138294215285
2.7169239322355936
2.7181459268249255
2.7182682371922975
2.7182804690957534
2.7182816941320818
2.7182817983473577
2.7182820520115603

Solution 3

You could use the mpmath (http://mpmath.org/) package here:

>>> import mpmath as mp
>>> f = lambda x: (1.0 + 1.0/x)**x
>>> mp.limit(f, mp.inf)
mpf('2.7182818284590451')
Share:
11,445
Ryan
Author by

Ryan

Updated on June 15, 2022

Comments

  • Ryan
    Ryan almost 2 years

    I want to calculate this expression:

    (1 + 1 / math.inf) ** math.inf,
    

    which should evaluates to e. However Python returns 1. Why is that?

    =====UPDATE========

    What I want to do here is to derive the effective annual rate from user's input, APR (annual percentage rate).

    def get_EAR(APR, conversion_times_per_year = 1):
        return (1 + APR / conversion_times) ** conversion_times - 1
    

    I would want this expression to also apply to continuous compounding. Yes I understand I can write if statements to differentiate continuous compounding from normal cases (and then I can use the constant e directly), but I would better prefer an integrated way.