SlideShare a Scribd company logo
1 of 30
Python Programming, 3/e 1
Python Programming:
An Introduction to
Computer Science
Lecture 5 / Chapter 3 in book
Computing with Numbers
Python Programming, 3/e 2
Objectives
 To understand the concept of data types.
 To be familiar with the basic numeric data types
in Python.
 To understand the fundamental principles of how
numbers are represented on a computer.
 To be able to use the Python Math library.
 To be able to read and write programs that
process numerical data.
Python Programming, 3/e 3
Numeric Data Types
 The information that is stored and manipulated by
computer programs is referred to as data.
 There are two different kinds of numbers!
 (5, 4, 3, 6) are whole numbers – they don’t have a
fractional part
 (.25, .10, .05, .01) are decimal fractions
 Inside the computer, whole numbers and decimal
fractions are represented quite differently!
 We say that decimal fractions and whole numbers
are two different data types.
Python Programming, 3/e 4
Numeric Data Types
 The data type of an object determines what
values it can have and what operations can be
performed on it.
 Whole numbers are represented using the
integer (int for short) data type.
 These values can be positive or negative whole
numbers.
Python Programming, 3/e 5
Numeric Data Types
 Python has a special function to tell us the
data type of any value.
>>> type(3)
<class 'int'>
>>> type(3.1)
<class 'float'>
>>> type(3.0)
<class 'float'>
>>> myInt = 32
>>> type(myInt)
<class 'int'>
>>>
Python Programming, 3/e 6
Numeric Data Types
 Why do we need two number types?
 Values that represent counts can’t be fractional
(you can’t have 3 ½ quarters)
 Most mathematical algorithms are very efficient
with integers
 The float type stores only an approximation to the
real number being represented!
 Since floats aren’t exact, use an int whenever
possible!
7
Numeric Data Types
Operations on ints
produce ints,
operations on floats
produce floats
(except for /).
8
Numeric Data Types
 Integer division produces a whole number.
 That’s why 10//3 = 3
 Think of it as ‘gozinta’, where 10//3 = 3 since 3 gozinta
(goes into) 10, 3 times (with a remainder of 1)
 10%3 = 1 is the remainder of the integer division of 10
by 3.
For more info on //: https://www.pythontutorial.net/advanced-python/python-floor-division/
Python Programming, 3/e 9
Rounding floats
 Python can also round floats, using the simple,
round() function
>>> round(7.36)
7
 Lets use it on Pi! - do you know, the number of Pi?
pi = 3.141592653589793
>>> round(pi, 3)
3.142
>>> round(3.6)
4
Python Programming, 3/e 10
Accumulating Results: Factorial
 How did we calculate 6!=6*5*4*3*2*1 ?
 6*5 = 30
 Take that 30, and 30 * 4 = 120
 Take that 120, and 120 * 3 = 360
 Take that 360, and 360 * 2 = 720
 Take that 720, and 720 * 1 = 720
Python Programming, 3/e 11
Accumulating Results: Factorial
 The general form of an accumulator
algorithm looks like this:
Initialize the accumulator variable
Loop until final result is reached
update the value of accumulator
variable
Python Programming, 3/e 12
Accumulating Results: Factorial
 It looks like we’ll need a loop!
fact = 1
for factor in [6, 5, 4, 3, 2, 1]:
fact = fact * factor
 For a random number n – we need a loop and
range accumulator to calculate n!
Range () method
Python Programming, 3/e 13
Range() method
Python Programming, 3/e 14
 What does range(n) return?
0, 1, 2, 3, …, n-1
 What does range(5) return? 0, 1, 2, 3, 4
 range has another optional parameter!
range(start, n) returns
start, start + 1, …, n-1
 But wait! There’s more!
range(start, n, step)
start, start+step, …, n-1
 list(<sequence>) to make a list
Python Programming, 3/e 15
Accumulating Results: Factorial
 Completed factorial program:
# factorial.py
# Program to compute the factorial of a number
# Illustrates for loop with an accumulator
def main():
n = eval(input("Please enter a whole number: "))
fact = 1
for factor in range(n,1,-1):
fact = fact * factor
print("The factorial of", n, "is", fact)
main()
Python Programming, 3/e 16
Using the Math Library
 Besides (+, -, *, /, //, **, %, abs), we have
lots of other math functions available in a
math library.
 A library is a module with some useful
definitions/functions.
Python Programming, 3/e 17
Using the Math Library
 Let’s write a program to compute the roots of a
quadratic equation!
 The only part of this we don’t know how to do is
find a square root… but it’s in the math library!
2
4
2
b b ac
x
a
  

Python Programming, 3/e 18
Using the Math Library
 To use a library, we need to make sure this line
is in our program:
import math
 Importing a library makes whatever functions are
defined within it available to the program.
Python Programming, 3/e 19
Using the Math Library
 To access the sqrt library routine, we need to
access it as math.sqrt(x).
 Using this dot notation tells Python to use the
sqrt function found in the math library module.
 To calculate the root, you can do
discRoot = math.sqrt(b*b – 4*a*c)
2
4
2
b b ac
x
a
  

20
2
4
2
b b ac
x
a
  

1) Let:
a= 1
b = 3
c = -4
2) Given formula 3) Plug numbers
Sqr 25 = 5
X1 = (-3 + 5)/2
X1 = 1
X2 = (-3 - 5)/2
X2 = -4
Solution 1 Solution 2
x^2 + 3x – 4 = 0 An example of a quadratic equation to try
 a*x^2 + b*x + c = 0.
2
4
2
b b ac
x
a
  

Python Programming, 3/e 21
Roots of quadratic equation
# quadratic.py
# A program that computes the real roots of a quadratic equation.
# Illustrates use of the math library.
# Note: This program crashes if the equation has no real roots.
import math # Makes the math library available.
def main():
print("This program finds the real solutions to a quadratic")
print()
a, b, c = eval(input("Please enter the coefficients (a, b, c): "))
discRoot = math.sqrt(b * b - 4 * a * c)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print()
print("The solutions are:", root1, root2 )
Python Programming, 3/e 22
This program finds the real solutions to a quadratic
Please enter the coefficients (a, b, c): 3, 4, -1
The solutions are: 0.215250437022 -1.54858377035
 What do you suppose this means?
This program finds the real solutions to a quadratic
Please enter the coefficients (a, b, c): 1, 2, 3
Traceback (most recent call last):
File "<pyshell#26>", line 1, in -toplevel-
main()
File "C:Documents and SettingsTerryMy DocumentsTeachingW04CS
120Textbookcodechapter3quadratic.py", line 14, in main
discRoot = math.sqrt(b * b - 4 * a * c)
ValueError: math domain error
>>>
Roots of quadratic equation
Python Programming, 3/e 23
Using the Math Library
 If a = 1, b = 2, c = 3, then we are trying to
take the square root of a negative number!
 Using the sqrt function is more efficient than
using **.
 How could you use ** to calculate a square
root? /power by 0.5/
Using the Math Library
Python Mathematics English
pi An approximation of pi
e e An approximation of e
sqrt(x) The square root of x
sin(x) sin x The sine of x
cos(x) cos x The cosine of x
tan(x) tan x The tangent of x
asin(x) arcsin x The inverse of sine x
acos(x) arccos x The inverse of cosine x
atan(x) arctan x The inverse of tangent x
log(x) ln x The natural (base e) logarithm of x
log10(x) The common (base 10) logarithm of x
exp(x) The exponential of x
ceil(x) The smallest whole number >= x
floor(x) The largest whole number <= x
24

x
10
log x
x
e
x
 
 
x
 
 
Quick conversion of numbers
 Type int(x) to convert x to a plain integer.
 Type long(x) to convert x to a long integer.
 Type float(x) to convert x to a floating-point number.
 Type complex(x) to convert x to a complex number
with real part x and imaginary part zero.
 Type complex(x, y) to convert x and y to a complex
number with real part x and imaginary part y. x and y
are numeric expressions
Python Programming, 3/e 25
Python Programming, 3/e 26
Mathematical functions (1)
abs(x) - The absolute value of x: the (positive) distance
between x and zero.
ceil(x) - The ceiling of x: the smallest integer not less than x.
cmp(x, y)
-1 if x < y, 0 if x == y, or 1 if x > y. Deprecated in Python 3.
Instead use return (x>y)-(x<y).
exp(x) - The exponential of x: e
x
fabs(x) - The absolute value of x.
floor(x) - The floor of x: the largest integer not greater than x.
log(x) - The natural logarithm of x, for x > 0.
Mathematical functions (2)
Python Programming, 3/e 27
log10(x) - The base-10 logarithm of x for x > 0.
max(x1, x2,...) - The largest of its arguments: the value closest to
positive infinity
min(x1, x2,...) - The smallest of its arguments: the value closest
to negative infinity.
modf(x) - The fractional and integer parts of x in a two-item
tuple. Both parts have the same sign as x. The integer part is
returned as a float.
pow(x, y) - The value of x**y.
round(x [,n]) - x rounded to n digits from the decimal point.
Python rounds away from zero as a tie-breaker: round(0.5) is 1.0
and round(-0.5) is -1.0.
sqrt(x) - The square root of x for x > 0.
Random number functions
Python Programming, 3/e 28
choice(seq) - A random item from a list, tuple, or string.
randrange ([start,] stop [,step]) - A randomly selected element from
range(start, stop, step).
random() - A random float r, such that 0 is less than or equal to r
and r is less than 1
seed([x]) - Sets the integer starting value used in generating random
numbers. Call this function before calling any other random module
function. Returns None.
shuffle(lst) - Randomizes the items of a list in place. Returns None.
uniform(x, y) - A random float r, such that x is less than or equal to r
and r is less than y.
Trigonometric functions
Python Programming, 3/e 29
acos(x) - Returns the arc cosine of x, in radians.
asin(x) - Returns the arc sine of x, in radians.
atan(x) - Returns the arc tangent of x, in radians.
atan2(y, x) - Returns atan(y / x), in radians.
cos(x) - Returns the cosine of x radians.
hypot(x, y) - Return the Euclidean norm, sqrt(x*x + y*y).
sin(x) - Return the sine of x radians.
tan(x) - Return the tangent of x radians.
degrees(x) - Converts angle x from radians to degrees.
radians(x) - Converts angle x from degrees to radians.
End of Lecture 5
Any questions?
30

More Related Content

Similar to Lecture 5 – Computing with Numbers (Math Lib).pptx

Introduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLVijaySharma802
 
python lab programs.pdf
python lab programs.pdfpython lab programs.pdf
python lab programs.pdfCBJWorld
 
Introduction to Python and Matplotlib
Introduction to Python and MatplotlibIntroduction to Python and Matplotlib
Introduction to Python and MatplotlibFrançois Bianco
 
1_Python Basics.pdf
1_Python Basics.pdf1_Python Basics.pdf
1_Python Basics.pdfMaheshGour5
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in PythonSumit Satam
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
Data Handling.pdf
Data Handling.pdfData Handling.pdf
Data Handling.pdfMILANOP1
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdfsimenehanmut
 
Python-CH01L04-Presentation.pptx
Python-CH01L04-Presentation.pptxPython-CH01L04-Presentation.pptx
Python-CH01L04-Presentation.pptxElijahSantos4
 

Similar to Lecture 5 – Computing with Numbers (Math Lib).pptx (20)

Introduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIML
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
python lab programs.pdf
python lab programs.pdfpython lab programs.pdf
python lab programs.pdf
 
See through C
See through CSee through C
See through C
 
Welcome to python workshop
Welcome to python workshopWelcome to python workshop
Welcome to python workshop
 
Introduction to Python and Matplotlib
Introduction to Python and MatplotlibIntroduction to Python and Matplotlib
Introduction to Python and Matplotlib
 
1_Python Basics.pdf
1_Python Basics.pdf1_Python Basics.pdf
1_Python Basics.pdf
 
Chapter08.pptx
Chapter08.pptxChapter08.pptx
Chapter08.pptx
 
Python programming
Python  programmingPython  programming
Python programming
 
Python basics
Python basicsPython basics
Python basics
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Data Handling.pdf
Data Handling.pdfData Handling.pdf
Data Handling.pdf
 
MODULE. .pptx
MODULE.                              .pptxMODULE.                              .pptx
MODULE. .pptx
 
Python basics
Python basicsPython basics
Python basics
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
 
Python-CH01L04-Presentation.pptx
Python-CH01L04-Presentation.pptxPython-CH01L04-Presentation.pptx
Python-CH01L04-Presentation.pptx
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Data Handling
Data Handling Data Handling
Data Handling
 

Recently uploaded

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 

Recently uploaded (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 

Lecture 5 – Computing with Numbers (Math Lib).pptx

  • 1. Python Programming, 3/e 1 Python Programming: An Introduction to Computer Science Lecture 5 / Chapter 3 in book Computing with Numbers
  • 2. Python Programming, 3/e 2 Objectives  To understand the concept of data types.  To be familiar with the basic numeric data types in Python.  To understand the fundamental principles of how numbers are represented on a computer.  To be able to use the Python Math library.  To be able to read and write programs that process numerical data.
  • 3. Python Programming, 3/e 3 Numeric Data Types  The information that is stored and manipulated by computer programs is referred to as data.  There are two different kinds of numbers!  (5, 4, 3, 6) are whole numbers – they don’t have a fractional part  (.25, .10, .05, .01) are decimal fractions  Inside the computer, whole numbers and decimal fractions are represented quite differently!  We say that decimal fractions and whole numbers are two different data types.
  • 4. Python Programming, 3/e 4 Numeric Data Types  The data type of an object determines what values it can have and what operations can be performed on it.  Whole numbers are represented using the integer (int for short) data type.  These values can be positive or negative whole numbers.
  • 5. Python Programming, 3/e 5 Numeric Data Types  Python has a special function to tell us the data type of any value. >>> type(3) <class 'int'> >>> type(3.1) <class 'float'> >>> type(3.0) <class 'float'> >>> myInt = 32 >>> type(myInt) <class 'int'> >>>
  • 6. Python Programming, 3/e 6 Numeric Data Types  Why do we need two number types?  Values that represent counts can’t be fractional (you can’t have 3 ½ quarters)  Most mathematical algorithms are very efficient with integers  The float type stores only an approximation to the real number being represented!  Since floats aren’t exact, use an int whenever possible!
  • 7. 7 Numeric Data Types Operations on ints produce ints, operations on floats produce floats (except for /).
  • 8. 8 Numeric Data Types  Integer division produces a whole number.  That’s why 10//3 = 3  Think of it as ‘gozinta’, where 10//3 = 3 since 3 gozinta (goes into) 10, 3 times (with a remainder of 1)  10%3 = 1 is the remainder of the integer division of 10 by 3. For more info on //: https://www.pythontutorial.net/advanced-python/python-floor-division/
  • 9. Python Programming, 3/e 9 Rounding floats  Python can also round floats, using the simple, round() function >>> round(7.36) 7  Lets use it on Pi! - do you know, the number of Pi? pi = 3.141592653589793 >>> round(pi, 3) 3.142 >>> round(3.6) 4
  • 10. Python Programming, 3/e 10 Accumulating Results: Factorial  How did we calculate 6!=6*5*4*3*2*1 ?  6*5 = 30  Take that 30, and 30 * 4 = 120  Take that 120, and 120 * 3 = 360  Take that 360, and 360 * 2 = 720  Take that 720, and 720 * 1 = 720
  • 11. Python Programming, 3/e 11 Accumulating Results: Factorial  The general form of an accumulator algorithm looks like this: Initialize the accumulator variable Loop until final result is reached update the value of accumulator variable
  • 12. Python Programming, 3/e 12 Accumulating Results: Factorial  It looks like we’ll need a loop! fact = 1 for factor in [6, 5, 4, 3, 2, 1]: fact = fact * factor  For a random number n – we need a loop and range accumulator to calculate n!
  • 13. Range () method Python Programming, 3/e 13
  • 14. Range() method Python Programming, 3/e 14  What does range(n) return? 0, 1, 2, 3, …, n-1  What does range(5) return? 0, 1, 2, 3, 4  range has another optional parameter! range(start, n) returns start, start + 1, …, n-1  But wait! There’s more! range(start, n, step) start, start+step, …, n-1  list(<sequence>) to make a list
  • 15. Python Programming, 3/e 15 Accumulating Results: Factorial  Completed factorial program: # factorial.py # Program to compute the factorial of a number # Illustrates for loop with an accumulator def main(): n = eval(input("Please enter a whole number: ")) fact = 1 for factor in range(n,1,-1): fact = fact * factor print("The factorial of", n, "is", fact) main()
  • 16. Python Programming, 3/e 16 Using the Math Library  Besides (+, -, *, /, //, **, %, abs), we have lots of other math functions available in a math library.  A library is a module with some useful definitions/functions.
  • 17. Python Programming, 3/e 17 Using the Math Library  Let’s write a program to compute the roots of a quadratic equation!  The only part of this we don’t know how to do is find a square root… but it’s in the math library! 2 4 2 b b ac x a    
  • 18. Python Programming, 3/e 18 Using the Math Library  To use a library, we need to make sure this line is in our program: import math  Importing a library makes whatever functions are defined within it available to the program.
  • 19. Python Programming, 3/e 19 Using the Math Library  To access the sqrt library routine, we need to access it as math.sqrt(x).  Using this dot notation tells Python to use the sqrt function found in the math library module.  To calculate the root, you can do discRoot = math.sqrt(b*b – 4*a*c) 2 4 2 b b ac x a    
  • 20. 20 2 4 2 b b ac x a     1) Let: a= 1 b = 3 c = -4 2) Given formula 3) Plug numbers Sqr 25 = 5 X1 = (-3 + 5)/2 X1 = 1 X2 = (-3 - 5)/2 X2 = -4 Solution 1 Solution 2 x^2 + 3x – 4 = 0 An example of a quadratic equation to try  a*x^2 + b*x + c = 0. 2 4 2 b b ac x a    
  • 21. Python Programming, 3/e 21 Roots of quadratic equation # quadratic.py # A program that computes the real roots of a quadratic equation. # Illustrates use of the math library. # Note: This program crashes if the equation has no real roots. import math # Makes the math library available. def main(): print("This program finds the real solutions to a quadratic") print() a, b, c = eval(input("Please enter the coefficients (a, b, c): ")) discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) print() print("The solutions are:", root1, root2 )
  • 22. Python Programming, 3/e 22 This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 3, 4, -1 The solutions are: 0.215250437022 -1.54858377035  What do you suppose this means? This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1, 2, 3 Traceback (most recent call last): File "<pyshell#26>", line 1, in -toplevel- main() File "C:Documents and SettingsTerryMy DocumentsTeachingW04CS 120Textbookcodechapter3quadratic.py", line 14, in main discRoot = math.sqrt(b * b - 4 * a * c) ValueError: math domain error >>> Roots of quadratic equation
  • 23. Python Programming, 3/e 23 Using the Math Library  If a = 1, b = 2, c = 3, then we are trying to take the square root of a negative number!  Using the sqrt function is more efficient than using **.  How could you use ** to calculate a square root? /power by 0.5/
  • 24. Using the Math Library Python Mathematics English pi An approximation of pi e e An approximation of e sqrt(x) The square root of x sin(x) sin x The sine of x cos(x) cos x The cosine of x tan(x) tan x The tangent of x asin(x) arcsin x The inverse of sine x acos(x) arccos x The inverse of cosine x atan(x) arctan x The inverse of tangent x log(x) ln x The natural (base e) logarithm of x log10(x) The common (base 10) logarithm of x exp(x) The exponential of x ceil(x) The smallest whole number >= x floor(x) The largest whole number <= x 24  x 10 log x x e x     x    
  • 25. Quick conversion of numbers  Type int(x) to convert x to a plain integer.  Type long(x) to convert x to a long integer.  Type float(x) to convert x to a floating-point number.  Type complex(x) to convert x to a complex number with real part x and imaginary part zero.  Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions Python Programming, 3/e 25
  • 26. Python Programming, 3/e 26 Mathematical functions (1) abs(x) - The absolute value of x: the (positive) distance between x and zero. ceil(x) - The ceiling of x: the smallest integer not less than x. cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y. Deprecated in Python 3. Instead use return (x>y)-(x<y). exp(x) - The exponential of x: e x fabs(x) - The absolute value of x. floor(x) - The floor of x: the largest integer not greater than x. log(x) - The natural logarithm of x, for x > 0.
  • 27. Mathematical functions (2) Python Programming, 3/e 27 log10(x) - The base-10 logarithm of x for x > 0. max(x1, x2,...) - The largest of its arguments: the value closest to positive infinity min(x1, x2,...) - The smallest of its arguments: the value closest to negative infinity. modf(x) - The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float. pow(x, y) - The value of x**y. round(x [,n]) - x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0. sqrt(x) - The square root of x for x > 0.
  • 28. Random number functions Python Programming, 3/e 28 choice(seq) - A random item from a list, tuple, or string. randrange ([start,] stop [,step]) - A randomly selected element from range(start, stop, step). random() - A random float r, such that 0 is less than or equal to r and r is less than 1 seed([x]) - Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None. shuffle(lst) - Randomizes the items of a list in place. Returns None. uniform(x, y) - A random float r, such that x is less than or equal to r and r is less than y.
  • 29. Trigonometric functions Python Programming, 3/e 29 acos(x) - Returns the arc cosine of x, in radians. asin(x) - Returns the arc sine of x, in radians. atan(x) - Returns the arc tangent of x, in radians. atan2(y, x) - Returns atan(y / x), in radians. cos(x) - Returns the cosine of x radians. hypot(x, y) - Return the Euclidean norm, sqrt(x*x + y*y). sin(x) - Return the sine of x radians. tan(x) - Return the tangent of x radians. degrees(x) - Converts angle x from radians to degrees. radians(x) - Converts angle x from degrees to radians.
  • 30. End of Lecture 5 Any questions? 30

Editor's Notes

  1. We have a few objectives lined up for today’s lecture and we’re touching upon a few mathematical concepts today but don’t worry, I will explain each before moving on to the next. To understand the concept of data types, which up to now, we’ve seen a few of but today, we’re specifically looking into numerical data types which is our 2nd objective – To be familiar with the basic numeric data types in Python. To understand the fundamental principles of how numbers are represented on a computer and how the different data types can change that. To understand the use of a specific library called Math Lib and how we can use it to run mathematical operations such as basic operations including finding floored quotients of x and y, floored division that is, exponentiation (raising powers), dividing floats by ints and vice versa etc. To be able to read and write programs that process numerical data and to do this, we’re going to use a simple program called quadratic.py in which we will attempt to work out a quadratic equation.
  2. Information stored and manipulated by computer programs is called data. We’ve all heard of data and data is everywhere but the way in which we represent this data in our computer programs matters. When it comes to specifically, numerical data, we have two data types to represent it. Namely, ints and floats. Ints are whole numbers and floats are numbers that contain decimal fractions/fractionals. Since floats have decimal fractions, it introduces incompleteness of data and it’s why we refer to floats as proximations of a real number or the result value. What I mean by this will hopefully become clear by the end of this lecture.
  3. By now, you already know that whole numbers are represented using ints but something to bear in mind is that ints can of course, be negative numbers as well. For exmaple, -1, -2, -1200 and so on are considered whole numbers and as such, we refer to them as integers and implement them syntactically using int keyword. When in doubt, we can use a python function called type in order to check the data type of any value.
  4. For example, to get the data type of this numerical value (click next) we call the function type (click next) and put the value in between the parenthesis which returns its data type (click next). As you can see, when we ask what is the data type of 3.1, the function type, returns float. In the last line syntax input, we declared myint variable and assigned 32 to it and when we want to find out the data type of this variable, we can do the same thing, type(myint) and the type function returns the data type of the value of this variable which is int of course, as it’s 32.
  5. The reason we need two number types is due to a number of things but primarly, we need them in order to correctly represent the values which in turn, gives us reason number 2, which is to be able to compute the different number types. In the past, the processing of ints was done very quickly and most importantly, very efficiently when compared to floats which required special arithmetic algorithms to process floats. But really, In modern computers, the hardware and processing power of processors is so optimised that I would say, this is useless point. In fact, what’s actually very important to focus on and remember, is the fact that floats – as you can imagine– as only approximations of real numbers. there is a limit to the precision, or accuracy, of the stored values unlike the case with ints which are absolute. So the general rule here is to only use floats if necessary. For example, working out how much change to give back requires floats but there’s no reason to use floats when working out how many people are on this session.
  6. Operations on ints produce ints, operations on floats produce floats (except for /). This means all mathematical operations involving ints will produce an int as a result except when there’s a division operation. In other words, Sum of ints is an int (click next) Multiplication of ints is int (click next) Floored quotient of 2 ints is an int (click next) – the double backslash indicates a floor division. Raising an int to the power of an int will result in an int. I.e., the exponentiation of ints (click next) for example, 5 to the power of 2 is 25, 2 to the power of 5 is 32. For those that don’t know this, raising x to a power is equivalent to multiplying x by the power. So 5 * 2 is equivalent to 5 * 5 which is 25, 2 to the power of 5 is 2*2*2*2*2, 5 times which is of course, 32 and so on. Now, in terms of float products, you will notice that even if we only ints by ints we still get a float which is not the same for other operations such as floor division where the result depends on the initial data type. If Floored division of 2 ints such as in line 8, we get int as a product, otherwise, it’s a float as you can see in line 9. What’s a floor division you ask, well lets have a look in the next slide but first, are there any questions up to this point at all?
  7. Ok, so what’s a floor division? So first, we need to understand the correct operator to use which the double divison or double back slash operator for floor division, as I said before. So, think about this way, how many times does 3 go into 10? The answer is 3 which is 9 and we’re left with 1, which is the remainder. Another example, what’s 10/4?.......The correct answer is 2.5 of course with a remainder of 2. Then, what’s the floored quotient of 10 and 4, so floor division of 10 by 4? The answer is 2 which means it returns the floor value (whole number). 10/4=2,5 <—-normal division 10//4=2 <—-floor division. For more info, I’ve attached a very useful link to learn more about floor division though this shouldn’t don’t spend too much time on this. The basics are already covered. This floor division operator is also called integer division operator as we can use it to always produce integer result. Otherwise, we can just the regular division operator which always returns a float. Now, let me ask you a quick question, how can we find out a remainder of a division instead? Suppose you want to find out how much is left of a given division ? The answer is to use another operator known as Modulo or Modulus Operator. This operator is denoted by the percentage symbole. So, 10 modulo 3 is 1 as 3 goes into 10, 3 times and leaves us with 1. therefor, the correct answer is 1. Another one, what about 6%3? The division of 6/3 is = 2 and there’s no remainder. Therefor, 6 modulo 3 is 0. Avoid----------- What about 3%5? It’s 3 of course, because we can’t devide as 5 is bigger than 3 – the right hand side of the modulo operator is greater than the left. 2&5 is 2, 1&5 is 1 and so on.
  8. In python, there’s a built-in function called round which can be very handy when working with numerical data types and maths operations in general. Lets see how this works with the value of Pi but first, does anybody know what the value of Pi is ? For those that don’t know this, It’s approx 3.14 (CLICK NEXT) but of course, since pi is an irrational number, its decimal form doesn’t end or repeat and the number of decimal places you see here is just 15 but as I said, it goes much further than this. Now, suppose you only need to know or work with the first 3 decimal places, how do you that? The answer is to round it to the 3rd decimal place using the round function. In python this means we use the round function with a second param to indicate the number of decimal places we want (CLICK NEXT). You can see in the second round call, we gave it a second param to specify the number of decimal places we need. If you look closer, something very interesting took place when we called the round function the first time, notice, we gave it a float 7.36 and it returned an int. This means, we can call the round function in this simple way to actually covert a float into an int validly. The opposite of this is the type conversion you see on the right hand-side (click next). What do you think is happening in both cases? Hint….Is it rounding, just like the round function? The answer is no, (CLICK NEXT) it’s actually cutting off the decimal point which is also known as truncation. So it just truncates the number and return everything before the decimal point (whole number). Where’s the round function So, two different ways of converting types but two very different results.
  9. In order for us to use some of these function such as math.floor(number) and some other functions, we need to work with a library called Math. To use it, we have to import it to our program using python import. If you can imagine a file or module, full of mathematical definitions and functions which we can use in an instance just by importing it to our program – we can use it in order to perform common mathematical tasks such as the one we’re about to see invovng working out the roots of a mathematical equation.
  10. Here’s what I’m referring to. Suppose we need to write a program that computes the roots of a quadratic equation. Just so I know, how many of you have encountered quadratic equations or learnt about it from college ? So, here’s the general formula to work out or in this case, compute the roots. You’ll know, in order to this correctly, we have to find the square root. We can do this by hand by where’s the fun in that? Lets do it syntactically. So first things first, (next page)
  11. We will need to use our beloved math library to make our lives easier. Somebody, somewhere has already done the work for us and included this work in what’s known as the math library. To use their work, we need to import it into our program. When we do that, whatever is contained in that library, becomes available for us to use instantly. We can import only one function (click next) from the library or the whole library or module itself (click next). Please note - this math library comes installed in python so there’s no need for any additional installation – just import it.
  12. Now, in order to compute the square root, we need a function called sqrt - short for square root. The math library has this routine or function which we can access by this dot notation (click next). Dot notation is called dot notation as we use the precedent (the name of the library) dot whatever specific function we want from this library. Now, to calculate root we can use this line discRoot = math.sqrt(b*b – 4*a*c) but where does b*b – 4 * a * c, so, where does it come from? And what is it? The answer is that, it comes from our formula that we’ve seen before – this one (Click next) and, it’s the formula to work out the square root. We have to compute the two roots as a direct result of this formula containing the +-. First, as addition and secondly, as subtraction.
  13. In order to program this, first let’s refresh our memory on how to do a quadratic equation So, we have here an example, x to the power of 2 + 3 times x – 4 = 0 (Click next) 1) Since there’s no co-efficient next to x to the power of 2, we assign 1 to a. 2) The value of b is given as 3, so let b = 3 and the value of c is given as -4. Now that we know this, we just need to plugs the numbers into the formula (click next). Square root of 25 is 5 which is the result of the calculation of (CLICK NEXT) 3^2 – 4 * 1 * (-4). As I said we plug in the numbers 1, 3 and -4 of a, b and c into the formula that’s all. Now, a rule to keep mind is when a square root is greater than 0, it means you will have to solutions to the quadratic equation. So we have to keep going to work out the second solution. In order words, because the square root is 25 and 25 is greater than 0, it means our quadratic equation will have 2 solutions. So now, we need to
  14. Right – so now that you have refreshed your memory on how to solve quadratic equations, let’s use Python and the math library to help us work it out instead. So, here’s the program as a whole. We have a main function inside of which, the program will compute the real roots of a quadratic equation. Now, a, b and c are our coefficients, and these are taken as input (click next), so the values are not known in advance. Instead, the user enters 3 numbers which we assign it to coefficients a, b and c respectively. Once the user provides us with this information we then calculate the square root of our discriminant (click next) using the math.sqrt library to do so. (b * b - 4 * a * c) > this is our discriminant. Once python work this out, it then needs to compute the value of each of the 2 equation roots (click next) which are the fraction denominator using the formula given and finally print the roots. Lets see an example,
  15. Here’s an example, 3, 4 and -1 respectively given by the user as coefficients. The results, are given as 0.2152 etc for root 1 and -1.548 etc for root 2. So that’s fine and understandable but look at what happens in the second instance we run the program. In the second run, the user enters different coeffecients. So a is given as 1, b is given as 2 and c as 3. When the user hits enter, the program crashes. Do you have any idea why this could be ? Try to plug in the numbers into the formula “(b * b - 4 * a * c)” (click next) Discrimnant of (2 ^ 2 minus 4 * 1 * 3) (click next) again just plugging in numbers, gives us (4 - 12) which gives square root of -8. Because it is impossible to compute a square root of a negative number, the equation doesn’t have roots and so the program throws the error. The square root gets calculated first and it gives us an indication as to the numbers of roots we will have. Having -8 means there are no roots as the value is negative. If instead, it was 0 then it means we have only 1 root and if it was a number greater than 0, it means we will have 2 roots.
  16. So yeah, I’ve already covered this as it turns out but we can also compute a square root of a discriminant using powers (**). Square root can be represented as a power of 1 over 2 / 1 devided by 2 or 0.5. So instead of using square root, we take the discriminant (b * b - 4 * a * c) and raise it to the power of 0.5.
  17. Here we have just an idea of what is included in the math library – of course, there’s more including functions on trigonometrics and many more. Whenever you want to use a function you see here or else where from the math library, remember to use the dot notation as I mentioned before. For example, if we wanted to use floor function we need to the library name which is math dot floor and then enter the numerical value inside the parenthesis. In order for this to work, we need to have imported the math library to begin with. After all, how can we use its functions without importing it. Notice, the sqrt function ? That’s the one we’ve just used to work out the square root. So that’s all for today’s session – I appreciate it’s packed but I’m sure going over the recording of this lecture and practicing during the workshop will help a great deal. During the workshop, your tutor and I will explain how the quadratic equation works in more detail Also, take a look at the last one, floor function. That’s also the one we’ve covered before but in relation to the floor division. This function returns the largest whole number that’s less than or equal to x or whatever number is inside the square brackets. For example, floor of 3.5 or 3,6 or 3,19 is 3.