Python Programming: An Introduction to Computer Science

(Nora) #1
32 CHAPTER3. COMPUTINGWITHNUMBERS

representa rangeofpositive andnegative integers. Now^2


32
2 ^2

(^31). So,therangeofintegersthatcanbe
representedina 32bitintvalueis 231 231  1.Thereasonforthe 1 onthehighendis toaccountfor
therepresentationof0 inthetophalfoftherange.
Let’s tryoutsomeexpressionsinPythontotestthisanalysis.Rememberthat**is thePythonexponen-
tiationoperator.





2 30
1073741824
2
31
Traceback (innermostlast):
File "", line1, in?
OverflowError: integerpow()
Pythoncancalculate 230 , but“blowsup”tryingtocompute 231. Youcanseethattheoverflowhappens
somewherebetweenthe30thand31stpoweroftwo.Thatis consistentwithouranalysisthatthelargestint
is 2^31  1.
Supposewetrytodisplaythelargestint.
2 31 - 1
Traceback (innermostlast):
File "", line1, in?
OverflowError: integerpow()
Ourfirsttrydidn’t work.Canyouseewhy?Pythonevaluatesthisexpressionbyfirsttryingtocalculate 2
31. ThatcalculationproducestheerrorbeforePythonhasa chancetosubtractone.
We needtobea littleclevererandsneakuponthevaluefromunderneath. We canusethefactthat
231 230  230. Strategicallysubtractingonefromeachsidegivesus 231  1 230  1  230. Bysubtracting
oneinthemiddleofthecomputation,wecanensurethattheintermediatevaluenevergetsbiggerthanthe
finalresult.Here’s whatPythonsays:
2 30 - 1 + 2 30
2147483647
Bytheway, thisexpressionillustratesanotherwaythatPythonintsdifferfromtheintegersthatthey
represent.Innormalarithmetic,thereis nodifferencebetween 231  1 and 230  1  230. They bothrepresent
thesamevalue.Incomputerarithmetic,however, oneis computableandtheotheris not!Representationsof
numbersdonotalwaysobey allthepropertiesthatwetake forgrantedwithnumbers.
Now thatwehave a numericvalue,wecandirectlytestourconjecturethatthisis thelargestint.
2147483647
2147483647
2147483648
OverflowError: integerliteral too large
Thereyouhave it.Thelargestintthatcanberepresentedin 32 bitsis 2 147  483 647.
Nowyouknowexactlywhyourprogramforfactorialcan’t compute13!.Thisvalueis largerthanthe
limitof 2  147  483 647.Naturally, thenextstepis tofigureouta wayaroundthislimitation.





3.5 HandlingLargeNumbers:LongInts.


Aslongasourfactorialprogramreliesontheintdatatype,wewillnotbeabletofindthefactorialoflarger
numbers.We needtouseanothernumerictype.Youmightfirstthinkofusinga floatinstead.Thisdoesnot
reallysolve ourproblem.Hereis anexamplerunofa modifiedfactorialprogramthatinitializesfacttothe
float 1 0.

Free download pdf