Python Programming: An Introduction to Computer Science

(Nora) #1
28 CHAPTER3. COMPUTINGWITHNUMBERS

root1 = (-b + discRoot)/ (2 * a)
root2 = (-b - discRoot)/ (2 * a)

print
print "The solutionsare:", root1, root2

main()


Thisprogrammakesuseofthesquarerootfunctionsqrtfromthemathlibrarymodule.Thelineat the
topoftheprogram:


import math


tellsPythonthatweareusingthemathmodule.Importinga modulemakeswhatever is definedinit available
totheprogram.To compute x, weusemath.sqrt(x). YoumayrecallthisdotnotationfromChapter1.
ThistellsPythontousethesqrtfunctionthat“lives”inthemathmodule. Inthequadraticprogramwe
calculate



b^2  4 acwiththeline

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


Hereis how theprogramlooksinaction:

This program findsthe real solutions to a quadratic


Please enter the coefficients(a, b, c): 3, 4, -2


The solutions are:0.387425886723 -1.72075922006


Thisprogramis fineaslongasthequadraticswetrytosolve have realsolutions.However, someinputs
willcausetheprogramtocrash.Here’s anotherexamplerun:


This program findsthe real solutions to a quadratic


Please enter the coefficients(a, b, c): 1, 2, 3
Traceback (innermostlast):
File "", line1, in?
File "quadratic.py",line 13, in?
discRoot = math.sqrt(b b - 4 a * c)
OverflowError: mathrange error


Theproblemhereis thatb^2  4 a c 0,andthesqrtfunctionis unabletocomputethesquarerootof
a negative number. Pythonprintsamath range error.Rightnow, wedon’t have thetoolstofixthis
problem,sowewilljusthave toassumethattheusergivesussolvableequations.
Actually,quadratic.pydidnotneedtousethemathlibrary. We couldhave takenthesquareroot
usingexponentiation**. (Canyouseehow?)Usingmath.sqrtis somewhatmoreefficientandallowed
metoillustratetheuseofthemathlibrary. Ingeneral,if yourprogramrequiresa commonmathematical
function,themathlibraryisthefirstplacetolook. Table3.2showssomeoftheotherfunctionsthatare
availableinthemathlibrary.


3.3 AccumulatingResults:Factorial


Supposeyouhave a rootbeersamplerpackcontainingsixdifferentkindsofrootbeer. Drinkingthevarious
flavorsindifferentordersmightaffecthow goodthey taste.If youwantedtotryouteverypossibleordering,
how many differentorderswouldtherebe?It turnsouttheansweris a surprisinglylargenumber, 720.Do
youknow wherethisnumbercomesfrom?Thevalue 720 is thefactorialof6.
Inmathematics,factorialis oftendenotedwithanexclamation(“!”).Thefactorialofa wholenumbern
is definedasn! n



n 1 


n 2 

1 . Thishappenstobethenumberofdistinctarrangementsfornitems.
Givensixitems,wecompute6!



6 


5 


4 


3 


2 


1  720 possiblearrangements.
Free download pdf