Python Programming: An Introduction to Computer Science

(Nora) #1
3.5.HANDLINGLARGENUMBERS:LONGINTS 33

Please enter a wholenumber. 15
The factorial of 15 is 1.307674368e+12


We donotgetanoverflow error, butwealsodonotgetanexactanswer.
Averylarge(orverysmall)floatingpointvalueis printedoutusingexponential, orscientific, notation.
Thee+12at theendmeansthattheresultis equalto 1 307674368 1012. Youcanthinkofthe+12at the
endasa markerthatshowswherethedecimalpointshouldbeplaced.Inthiscase,it mustmove 12placesto
therighttogettheactualvalue.However, thereareonly9 digitstotherightofthedecimal,sowehave “lost”
thelastthreedigits.
Remember, floatsareapproximations.Usinga floatallowsustorepresenta muchlargerrangeofvalues,
buttheamountofprecisionis stillfixed.Infact,a computerstoresfloatingpointnumbersasa pairoffixed-
length(binary)integers.Oneintegerrepresentsthestringofdigitsinthevalue,andthesecondrepresentsthe
exponentvaluethatkeepstrackofwherethewholepartendsandthefractionalpartbegins.
Fortunately, Pythonprovidesa bettersolutionforlarge,exactvaluesintheformofa thirdnumerictype
longint. A longintis nota fixedsize,butexpandstoaccommodatewhatever valueit holds.Theonlylimitis
theamountofmemorythecomputerhasavailabletoit.To geta longint,youputan“L” suffixona numeric
literal.So,theliteral 5 is anintrepresentationofthenumberfive, but5Lis a longintrepresentationofthe
numberfive.Ofcourse,fora numberthissmall,thereis noreasontousea longint.However, usinga long
intcausesPythontouselongintoperations,andourvaluecangrow to any size.Herearesomeexamplesthat
illustrate:





2L
2L
2L ** 31
2147483648L
type(100L)
<type ’long int’>
10000000000000000000000000000000000000L + 25
10000000000000000000000000000000000 025L





Noticehow calculationsinvolvinga longintproducea longintresult.Usinglongintsallowsustocompute
withreallylargenumbers.
We canmodifyourfactorialprogramtouselongintbysimplyinitializingfactto1L. Sincewestart
witha longint,eachsuccessive multiplicationwillproduceanotherlongint.


factorial2.py


def main():
n = input("Pleaseenter a whole number: ")
fact = 1L # Usea long int here
for factor in range(n,0,-1):
fact = fact* factor
print "The factorialof", n, "is", fact


Now wecantake thefactorialofarbitrarilylargeinputs.





import factorial2
Please enter a wholenumber: 13
The factorial of 13 is 6227020800








factorial2.main()
Please enter a wholenumber: 100
The factorial of 100 is 933262154439441526816992388562667 004907159682
643816214685929638952175999932299156089414639761565182862536979208272
23758251185210916864000000000000000000000000




Free download pdf