3.4.THELIMITSOFINT 31
3.4 TheLimitsofInt
Sofar, I have talkedaboutnumericdatatypesasrepresentationsoffamiliarnumberssuchasintegersand
decimalfractions.It is importanttokeepinmind,however, thatthesenumerictypesarejustrepresentations,
andthey donotalwaysbehave exactlylike thenumbersthatthey represent.We canseeanexampleofthisas
wetestoutournew factorialprogram.
import factorial
Please enter a wholenumber: 6
The factorial of 6 is 720
factorial.main()
Please enter a wholenumber: 10
The factorial of 10 is 3628800
factorial.main()
Please enter a wholenumber: 13
Traceback (innermostlast):
File "", line1, in?
File "factorial.py",line 9, in main
fact = fact * factor
OverflowError: integermultiplication
Everythingseemsfineuntilwetrytocomputethefactorialof13.Whencomputing13!theprogramprints
outanOverflowErrormessage.Whatis goingonhere?
Theproblemis thatthisprogramis representingwholenumbersusingPython’s intdatatype.Unfortu-
nately, intsarenotexactlylike mathematicalintegers.Thereareinfinitelymany integers,butonlya finite
rangeofints.Insidethecomputer, intsarestoredina fixed-sizedbinaryrepresentation.To make senseof
this,weneedtolookat what’s goingonat thehardwarelevel.
Computermemoryis composedofelectrical“switches,” eachofwhichcanbeinoneoftwo possible
states,basicallyonoroff. Eachswitchrepresentsa binarydigitorbitofinformation.Onebitcanencodetwo
possibilities,usuallyrepresentedwiththenumerals0 (foroff) and1 (foron).A sequenceofbitscanbeused
torepresentmorepossibilities.Withtwo bits,wecanrepresentfourthings.
bit 2 bit 1
0 0
0 1
1 0
1 1
Threebitsallowustorepresenteightdifferentvaluesbyaddinga zerooronetoeachofthefourtwo-bit
patterns.
bit 3 bit 2 bit 1
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
Youcanseethepatternhere.Eachextrabitdoublesthenumberofdistinctpatterns.Ingeneral,nbitscan
represent 2 ndifferentvalues.
Thenumberofbitsthata particularcomputerusestorepresentanintdependsonthedesignoftheCPU.
TypicalPCstodayuse 32 bits.Thatmeansthereare 232 possiblevalues.Thesevaluesarecenteredat0 to