Calulation in lim (1 + 1 /n) ^n when n -> infinite

Oscar Benjamin oscar.j.benjamin at gmail.com
Mon Nov 9 07:50:34 EST 2015


On 9 November 2015 at 12:21, Salvatore DI DIO <artyprog at gmail.com> wrote:
> I was trying to show that this limit was 'e'
> But when I try large numbers I get errors
>
> def lim(p):
>     return math.pow(1 + 1.0 / p , p)
>
>>>> lim(500000000)
> 2.718281748862504
>>>> lim(900000000)
> 2.7182820518605446  !!!!
>
>
> What am i doing wrong ?

You're performing a floating point calculation and expecting exact results.

Try this:

    >>> lim(10 ** 17)
    1.0

Why does this happen? Well in this case that number is 10**17 and it
turns out that

    >>> 1 + 1.0 / 10**17
    1.0

This is because there aren't enough digits in double precision
floating point to represent the difference between 1 and 1+1e-17. As p
gets larger the addition 1+1.0/p because less and less accurate. The
error in computing that is amplified by raising to a large power p.

You can use more digits by using the decimal module:

    >>> from decimal import Decimal, localcontext
    >>> def lim(p):
    ...     return (1 + 1 / Decimal(p)) ** p
    ...
    >>> with localcontext() as ctx:
    ...     ctx.prec = 100
    ...     lim(10**17)
    ...
    Decimal('2.718281828459045221768878329057436445543726874642885850945607978722364313911964199165598158907225076')

You can also install sympy and find this result symbolically:

    >>> from sympy import Symbol, limit, oo
    >>> p = Symbol('p', integer=True)
    >>> limit((1 + 1/p)**p, p, oo)
    E

--
Oscar



More information about the Python-list mailing list