[Tutor] value of 'e'
Kent Johnson
kent37 at tds.net
Tue Nov 24 13:26:57 CET 2009
On Tue, Nov 24, 2009 at 6:47 AM, Shashwat Anand
<anand.shashwat at gmail.com> wrote:
> Followed by this discussion on Hacker News I checked this link and was
> wondering how to calculate value of 'e' to a large extent
>
> as e = 1/0! + 1/1! +1/2! .... and so on...
> so i wrote this:
>>>> sum(1.0 / math.factorial(i) for i in range(100))
> 2.7182818284590455
>
> It was not giving the precision that I wanted so I tried decimal module of
> which I was not much aware of.
>
>>>> decimal.getcontext().prec = 100
>>>> sum(decimal.Decimal(str(1./math.factorial(decimal.Decimal(i)))) for i in
>>>> range(100))
You are using floating point division here. The argument to
math.factorial() is an integer, so the conversion of i to Decimal is
not doing anything - it is converted back to an integer. Then you
compute 1./<some large integer>. This will use floating point math and
will fail when the factorial is too large to represent in floating
point.
You should convert the result of factorial() to Decimal and compute
Decimal(1.0)/Decimal(<factorial>). This should give you additional
precision as well.
Kent
More information about the Tutor
mailing list