Python Programming: An Introduction to Computer Science

(Nora) #1
3.2.USINGTHEMATHLIBRARY 27

>>> 3.0 * 4.0

12.0

>>> 3 * 4

12

>>> 10.0 / 3.0

3.33333333333

>>> 10 / 3

3

>>> 10 % 3

1




abs(5)
5
abs(-3.5)
3.5





Noticehowoperationsonfloatsproducefloats,andoperationsonintsproduceints.Mostofthetime,we
don’t have toworryaboutwhattypeofoperationis beingperformed;forexample,integeradditionproduces
prettymuchthesameresultasfloatingpointaddition.
However, inthecaseofdivision,theresultsarequitedifferent. Integerdivisionalwaysproducesan
integer, discardingany fractionalresult.Thinkofintegerdivisionas“gozinta.” Theexpression,10 / 3
produces3 becausethreegozinta(goesinto)tenthreetimes(witha remainderofone). Thethirdtolast
exampleshowstheremainderoperation(%) inaction.Theremainderofdividing 10 by3 is 1.Thelasttwo
examplesillustratetakingtheabsolutevalueofanexpression.
YoumayrecallfromChapter2 thatSuzieProgrammerusedtheexpression9.0 / 5.0inhertempera-
tureconversionprogramratherthan9 / 5. Now youknow why. Theformergivesthecorrectmultiplierof
1 8, whilethelatteryieldsjust1, since5 gozinta9 justonce.


3.2 UsingtheMathLibrary.


BesidestheoperationslistedinTable3.1,Pythonprovidesmany otherusefulmathematicalfunctionsina
specialmathlibrary. Alibraryisjusta modulethatcontainssomeusefuldefinitions.Ournextprogram
illustratestheuseofthislibrarytocomputetherootsofquadraticequations.
A quadraticequationhastheformax^2  bx c 0.Suchanequationhastwo solutionsforthevalueof
xgivenbythequadraticformula:


x

 b


b^2  4 ac
2 a

Let’s writea programthatcanfindthesolutionstoa quadraticequation.Theinputtotheprogramwillbethe
valuesofthecoefficientsa,b, andc. Theoutputsarethetwo valuesgivenbythequadraticformula.Here’s a
programthatdoesthejob.


quadratic.py


A program thatcomputes the real roots of a quadratic equation.


Illustrates use of the mathlibrary.


Note: this programcrashes if the equation has no real roots.


import math # Makesthe math library available.


def main():
print "This programfinds the real solutions to a quadratic"
print


a, b, c = input("Please enter the coefficients (a, b, c): ")

discRoot = math.sqrt(b* b - 4 * a * c)
Free download pdf