On Mon, Nov 9, 2015 at 11:21 PM, Salvatore DI DIO <artyp...@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 ? >
Floating point error is going to start becoming a major problem here. Eventually, 1.0/p will underflow to zero, and you'll simply get a result of 1.0: >>> lim(900000000000000000000) 1.0 You could try using decimal.Decimal instead; that can give you rather more precision. Or if you have a lot of patience, fractions.Fraction. >>> def lim(p): return (1 + decimal.Decimal(1) / p) ** p >>> lim(500000000) Decimal('2.718281825740763411884758912') >>> lim(900000000) Decimal('2.718281826948888665260445479') >>> lim(900000000000000000000) Decimal('2.718281556630875980862943027') Definitely not perfect yet... but let's crank up the precision. >>> decimal.getcontext().prec=200 >>> lim(500000000) Decimal('2.7182818257407634118847589119866382434352189174535941028176465917058364010909850212743201574998148959449308935216863472501568773422911827403060031110458945666576132256505421665510943751730347310393611') >>> lim(900000000) Decimal('2.7182818269488886655322736616533366198705073189604924113513719666470682138645212144697520852594221964992741852547403862053248620085931699038380869918694830598723560639286551799819233225160142059050076') >>> lim(900000000000000000000) Decimal('2.7182818284590452353587773147812963615153818054494196724217932791045775211554493949916225628968841872263472976692247791433837657091684393783360159727396877123886624050885921242672885287748600658242797') Now we're starting to get pretty close to the actual value of e. You can push the precision further if you like; it'll take longer to calculate, and dump a bigger pile of digits onto your screen, but it'll be more accurate. I don't recommend using fractions.Fraction unless you have a really fast computer and a LOT of patience. It'll take three parts of forever to get a result... but that result _will_ be perfectly accurate :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list