SlideShare a Scribd company logo
1 of 45Module 5 : Numbers and Built‐in Functions
Introduction to       
Computational Thinking
Module 5 :
Numbers and Built‐in Functions
Asst Prof Chi‐Wing FU, Philip
Office: N4‐02c‐104
email: cwfu[at]ntu.edu.sg
2 of 45Module 5 : Numbers and Built‐in Functions
Topics
• More on Numbers
• Built-in functions
• Comparing floating point numbers
• Case Study: Finding Square Root
• Self Study: Bitwise operators (optional)
3 of 45Module 5 : Numbers and Built‐in Functions
More on Numbers
• Integers and Floating point numbers
• Their representations in computers
• Data range
• Optional: Bitwise operators on integers
4 of 45Module 5 : Numbers and Built‐in Functions
Memory: Bits and Bytes
• 1 Byte = 8 bits (each bit either 0 or 1)
• 1 Byte has 28 different variations, i.e., 256
• How about 4 bytes?
0
0
0
0
0
0
0
0 0
0
00
1
11
1
1
1
1
1
1
1111000
1001
1002
Contents of
memory
Memory
This is also covered in
Introduction to Computing Systems
5 of 45Module 5 : Numbers and Built‐in Functions
Integers (others)
• In most programming languages, an
integer takes up 4 bytes. The first bit for
sign: +ve or -ve, i.e., 31 bits left
• Since there is a zero needed to be
represented (as all zeros in the 32 bits),
the available data range is [-231, +231 – 1 ]
6 of 45Module 5 : Numbers and Built‐in Functions
Integers (Python)
• Integers in Python has unlimited precision
• This is a useful feature in Python; otherwise,
we (programmers) have to handle them
ourselves through programming effort
7 of 45Module 5 : Numbers and Built‐in Functions
Float
• For real numbers with decimals
• Limited precision because we use limited
number of bits to store the data in a special
format (you will learn later in other course):
• Max. representable finite float
• Min. positive normalized float
Want to know more? http://docs.python.org/tutorial/floatingpoint.html
http://en.wikipedia.org/wiki/Double_precision_floating-point_format
8 of 45Module 5 : Numbers and Built‐in Functions
Float
• and it has limited precision…
• Hence, computation results with floats
may not be exact
9 of 45Module 5 : Numbers and Built‐in Functions
Integer VS Float
• When writing programs, variables that are
numeric can be integers or floats
• So… how to choose?
Think about the context!!!
Need decimal values? Want precision?
10 of 45Module 5 : Numbers and Built‐in Functions
Integer VS Float
• For the followings, which type is
more appropriate?
• Age
• Height
• Volume of a container
• Exchange rate
• Voltage and current
• Number of students in a class
• Bank account balance
11 of 45Module 5 : Numbers and Built‐in Functions
Topics
• More on Numbers
• Built-in functions
• Comparing floating point numbers
• Case Study: Finding Square Root
• Self Study: Bitwise operators (optional)
12 of 45Module 5 : Numbers and Built‐in Functions
What are Built-in functions
• Built-in functions are subroutines, procedures,
or methods that are built into Python itself; each
provides a specific functionality
• See the Python standard library:
http://docs.python.org/library/functions.html
• In fact, you knew some of them already:
• print (for displaying data)
• input (for reading user input)
• float, int, str (for converting data)
• type (for checking data type)
• exec (for executing a string in Python), …, etc.
13 of 45Module 5 : Numbers and Built‐in Functions
• abs(x) – Return absolute value of x
• min(x,y) and max(x,y) – Return minimum
and maximum of x and y, respectively
They allow two or
more arguments
Let’s learn more: calling & arg(s)
Takes one argument
14 of 45Module 5 : Numbers and Built‐in Functions
More Built-in Functions
• math.ceil(x) and math.floor(x) –
Return the ceiling and floor of x as “int”
Remember to
import math
15 of 45Module 5 : Numbers and Built‐in Functions
More Built-in Functions
• math.pow(x,y) – Return x raised to the power y
• math.sqrt(x) – Return the square root of x
• math.log(x) – Return natural logarithm of x
• math.log10(x) – Return base-10 logarithm of x
Math functions
usually return
“float”
16 of 45Module 5 : Numbers and Built‐in Functions
More Built-in Functions
• math.sin(x), math.cos(x), math.tan(x)
– Return the sine, cosine, and tangent of x (radian)
• math.asin(x),math.acos(x),math.atan(x)
– Return arc sin, cos, and tan of x in radian
(Note: they all use radian!)
• math.degrees(x) and math.radians(x)
– Return x in degrees and radians, respectively
17 of 45Module 5 : Numbers and Built‐in Functions
Help Function
• help(“...”) – display help information on a
Python function or module
18 of 45Module 5 : Numbers and Built‐in Functions
Topics
• More on Numbers
• Built-in functions
• Comparing floating point numbers
• Case Study: Finding Square Root
• Self Study: Bitwise operators (optional)
19 of 45Module 5 : Numbers and Built‐in Functions
No Equality!
• If we want to know if two floating point numbers
are equal or not, can we use "==" ??
• It is tricky!!!
They are not equal! Why?
So… how to fix it?
20 of 45Module 5 : Numbers and Built‐in Functions
So… how to check?
• First, we can define a relatively small floating
point value, usually called epsilon or tolerance
• IDEA: if the absolute difference between the
two floating point numbers is smaller than
epsilon, we say that their values are the same
Key idea!!!!
(computationally but not mathematically)
21 of 45Module 5 : Numbers and Built‐in Functions
Topics
• More on Numbers
• Built-in functions
• Comparing floating point numbers
• Case Study: Finding Square Root
• Self Study: Bitwise operators (optional)
22 of 45Module 5 : Numbers and Built‐in Functions
Case Study
• Here we want to implement an algorithm to
compute the square root of a value without
using math.sqrt
You should implement, run, and try the case
study yourself in the course
23 of 45Module 5 : Numbers and Built‐in Functions
Algorithm: compute square root
• We can compute the square root of a value,
say x, iteratively using the following idea:
Given x,
first compute an initial guess: guess = x/2
then diff = guess* guess - x
if abs(diff) < epsilon, we are done
if diff > 0, guess is too large
if diff < 0, guess is too small
update guess so that it gets closer, then
Repeat
24 of 45Module 5 : Numbers and Built‐in Functions
Algorithm: compute square root
• But… how to update guess so that it gets
closer in every iteration…
• Let’s check x/guess…
In case x=100 and guess=50,
x/guess = 2
the targeting square root value should always
lie between guess and x/guess!
• So… we may update guess as mean value of
guess and x/guess and make it closer!
25 of 45Module 5 : Numbers and Built‐in Functions
Algorithm: compute square root
Let’s do this test…
• Iteration #1
x=100 and guess=50
x/guess=2 -> new guess = mean = 26
• Iteration #2
x=100 and guess=26
x/guess=3.846 -> new guess = mean = 14.923
• Iteration #3
x=100 and guess=14.923
x/guess=6.701 -> new guess = mean = 10.812
…………
Really getting closer and closer!!!
26 of 45Module 5 : Numbers and Built‐in Functions
Implementation
• Here is the Python implementation
We will learn “while” in module 6.2
27 of 45Module 5 : Numbers and Built‐in Functions
Implementation
• Add variable "iter" to count number of iterations
Add iteration counter
28 of 45Module 5 : Numbers and Built‐in Functions
Verification… by math.sqrt
• Lastly… we must verify our program!!!
Report the difference
This is a verification
29 of 45Module 5 : Numbers and Built‐in Functions
Testing #1
• We try with x = 100
Our result
Difference is very small
30 of 45Module 5 : Numbers and Built‐in Functions
Testing #2
• We try with x = 100000
Our result
But…
need more
iterations for
larger num.
Difference
still small
31 of 45Module 5 : Numbers and Built‐in Functions
Testing #3
• Lastly… try with x = 2
Difference is still very small
Fewer
iterations
this time
Our result
32 of 45Module 5 : Numbers and Built‐in Functions
Topics
• More on Numbers
• Built-in functions
• Comparing floating point numbers
• Case Study: Finding Square Root
• Self Study: Bitwise operators (optional)
33 of 45Module 5 : Numbers and Built‐in Functions
What are Bitwise operators
• Recall that integers are stored in binary, e.g.,
34 of 45Module 5 : Numbers and Built‐in Functions
NOT~
SHIFT (right)>>
SHIFT (left)<<
Bitwise XOR^
Bitwise OR|
Bitwise AND&
meaningoperator
What are Bitwise operators
• Python provides bitwise operators that process
input integers bit by bit correspondingly
• Treat 1 as true and 0 as false
Input:
15 -> 0000 1111
17 -> 0001 0001
What is 15 | 17 ?
All are binary
operations except ~,
which is unary
35 of 45Module 5 : Numbers and Built‐in Functions
00 & 0
00 & 1
01 & 0
11 & 1
ResultAND
Truth tables of &, |, ^, ~
00 | 0
10 | 1
11 | 0
11 | 1
ResultOR
00 ^ 0
10 ^ 1
11 ^ 0
01 ^ 1
ResultXOR
• XOR is called exclusive or; it is true ONLY if one
of the two bits is true (but not both)
• ~x is a special operation called 2’s complement,
which is just -x-1, i.e., ~2 gives -3
36 of 45Module 5 : Numbers and Built‐in Functions
Examples: &, |, ^
&
|
^
37 of 45Module 5 : Numbers and Built‐in Functions
Examples: shift <<, >>
<<
>>
38 of 45Module 5 : Numbers and Built‐in Functions
3 << 1 gives 6SHIFT (left)<<
~3 gives -4NOT~
3 >> 1 gives 1SHIFT (right)>>
3 ^ 2 gives 1Bitwise XOR^
3 | 2 gives 3Bitwise OR|
3 & 2 gives 2Bitwise AND&
examplesmeaningoperator
More examples
Try to work them out yourself
39 of 45Module 5 : Numbers and Built‐in Functions
Any Application?
1. Simple Data Encryption and Decryption
using the xor operator
2. Pseudo Random Number Generator
(PRNG)
40 of 45Module 5 : Numbers and Built‐in Functions
Application #1
• xor can be used for doing simple encryption
and decryption
• Given
D – our data (any integer, i.e., 32 bits)
K – our key in encryption (which is an integer)
• We can perform encryption by:
E = D xor K where E is the encrypted integer
• and decryption by
E xor K gives D
We can recover D from E using K
XOR has this interesting property
Why? Study the truth table…
41 of 45Module 5 : Numbers and Built‐in Functions
Application #2
• Pseudo Random Number Generator (PRNG):
• Seed – A number to initialize the generator
• Random number sequence – Use seed as
input, we apply the generator to obtain the first
random number; then use it as input to
generate the next random number, and so on…
See http://docs.python.org/library/random.html
• In designing a PRNG, bitwise operations are
often used, see next slide for a simple example
Interesting article:
http://spectrum.ieee.org/semiconductors/processors/behind-intels-new-randomnumber-generator
42 of 45Module 5 : Numbers and Built‐in Functions
Application #2 (cont.)
• Example: Define a function “parityOf” to
compute the parity of an integer:
A bit to add to an integer to make the
number of 1s in its binary form to be even
Define a simple 12-bit PRNG
A sequence of random number
(binary numbers) can be
generated starting from the seed
note: 0x indicates
hexidecimal format
43 of 45Module 5 : Numbers and Built‐in Functions
Application #2 (cont.)
• Note:
• You will learn how to use Python keyword “def” to
define functions later in this course
• Using bitwise operators, we can efficiently compute the
parity and develop pseudorandom number generators.
There are many PRNGs in the world; some are more
complicated, and they could have different quality…
• Since the numbers generated in the example code
form a binary number sequence, we also call it a
Pseudo Random Binary Sequence Generator (PRBSG)
• Related courses in the future:
“Computer Organization and Architecture” and
“Microprocessor-based System Design”
44 of 45Module 5 : Numbers and Built‐in Functions
Take Home Messages
• Integers, Long, and Floating point numbers
– Representation and property: data range, minimum and
maximum values, and precision
• Built-in functions are useful resources built into
Python itself
• Comparing floating point numbers can be tricky
(and error-prone)
– Use absolute difference against a small epsilon to test
equality for floating point numbers
45 of 45Module 5 : Numbers and Built‐in Functions
Reading Assignment
• Textbook
Chapter 1: Beginnings
1.8 to 1.10
Note: Though some material (1.10) in textbook is
not directly related to the lecture material, you can
learn more from them.

More Related Content

PDF
Algorithms Lecture 3: Analysis of Algorithms II
PDF
Algorithms Lecture 1: Introduction to Algorithms
PDF
01 Analysis of Algorithms: Introduction
PDF
Algorithms Lecture 2: Analysis of Algorithms I
PPTX
Algorithms - "Chapter 2 getting started"
Algorithms Lecture 3: Analysis of Algorithms II
Algorithms Lecture 1: Introduction to Algorithms
01 Analysis of Algorithms: Introduction
Algorithms Lecture 2: Analysis of Algorithms I
Algorithms - "Chapter 2 getting started"

What's hot (20)

PDF
Algorithm chapter 2
PPT
chapter 1
PDF
Matlab solved problems
PPTX
Analysis of algorithm
PDF
Matlab tutorial 4
PDF
Lecture5 syntax analysis_1
PPT
01 intro to algorithm--updated 2015
PDF
Design & Analysis Of Algorithm
PPT
Design and analysis of Algorithm By Dr. B. J. Mohite
PPT
PPTX
Algorithm analysis (All in one)
PPT
Data Structures and Algorithm Analysis
ODP
(2) cpp imperative programming
PPTX
Searching techniques with progrms
PPTX
Programming Logic and Design: Working with Data
PDF
Daa notes 1
PDF
Lecture6 syntax analysis_2
PPTX
Recursion | C++ | DSA
PPTX
MATLAB - The Need to Know Basics
PPTX
Recurrence Relation
Algorithm chapter 2
chapter 1
Matlab solved problems
Analysis of algorithm
Matlab tutorial 4
Lecture5 syntax analysis_1
01 intro to algorithm--updated 2015
Design & Analysis Of Algorithm
Design and analysis of Algorithm By Dr. B. J. Mohite
Algorithm analysis (All in one)
Data Structures and Algorithm Analysis
(2) cpp imperative programming
Searching techniques with progrms
Programming Logic and Design: Working with Data
Daa notes 1
Lecture6 syntax analysis_2
Recursion | C++ | DSA
MATLAB - The Need to Know Basics
Recurrence Relation
Ad

Viewers also liked (20)

PDF
Lecture 2 introduction to python
PDF
Python 3 Days
PDF
Lecture 0 beginning
PDF
Lecture 4 variables data types and operators
PDF
Lecture 6.1 flow control selection
PDF
Lecture 6.2 flow control repetition
PDF
Lecture 7 program development issues (supplementary)
PDF
Lecture 8 strings and characters
PDF
Python Tutorial
PDF
Lecture 11 file management
PPTX
Play with python lecture 2
PDF
Lecture 10 user defined functions and modules
PDF
Introduction to WEB HTML, CSS
PPTX
Python GUI Course Summary - 7 Modules
PPTX
Programming for Everybody in Python
PDF
Lecture 1 computing and algorithms
PDF
Training Google Drive and Hangouts.pptx
PDF
Python - Lecture 1
PDF
Lecture 12 exceptions
Lecture 2 introduction to python
Python 3 Days
Lecture 0 beginning
Lecture 4 variables data types and operators
Lecture 6.1 flow control selection
Lecture 6.2 flow control repetition
Lecture 7 program development issues (supplementary)
Lecture 8 strings and characters
Python Tutorial
Lecture 11 file management
Play with python lecture 2
Lecture 10 user defined functions and modules
Introduction to WEB HTML, CSS
Python GUI Course Summary - 7 Modules
Programming for Everybody in Python
Lecture 1 computing and algorithms
Training Google Drive and Hangouts.pptx
Python - Lecture 1
Lecture 12 exceptions
Ad

Similar to Lecture 5 numbers and built in functions (20)

PPTX
ESCM303 Introduction to Python Programming.pptx
PPTX
Python4HPC.pptx
PPTX
Python4HPC.pptx
PPTX
Python details for beginners and for students
PDF
Functional Python Webinar from October 22nd, 2014
PPTX
Python Introduction controll structures and conprehansion
PPTX
python ppt
PPTX
Computer Studies 2013 Curriculum framework 11 Notes ppt.pptx
PPTX
Updatedpython.pptxUpdatedpython.pptxUpdatedpython.pptx
PDF
Introduction to Python for Plone developers
PPT
Basic elements of java
PDF
Lecture 1 (bce-7)
PDF
ReiBoot 10.11.0 Crack With Registration Code Free Do[2025]
PDF
04 Functional Programming in Python
PPTX
Functions, List and String methods
PPTX
Basic concept of Python.pptx includes design tool, identifier, variables.
PPTX
Unit 2 algorithm
PPTX
1.4 Work with data types and variables, numeric data, string data.pptx
PPTX
if, while and for in Python
PPTX
Review of C programming language.pptx...
ESCM303 Introduction to Python Programming.pptx
Python4HPC.pptx
Python4HPC.pptx
Python details for beginners and for students
Functional Python Webinar from October 22nd, 2014
Python Introduction controll structures and conprehansion
python ppt
Computer Studies 2013 Curriculum framework 11 Notes ppt.pptx
Updatedpython.pptxUpdatedpython.pptxUpdatedpython.pptx
Introduction to Python for Plone developers
Basic elements of java
Lecture 1 (bce-7)
ReiBoot 10.11.0 Crack With Registration Code Free Do[2025]
04 Functional Programming in Python
Functions, List and String methods
Basic concept of Python.pptx includes design tool, identifier, variables.
Unit 2 algorithm
1.4 Work with data types and variables, numeric data, string data.pptx
if, while and for in Python
Review of C programming language.pptx...

Recently uploaded (20)

PDF
Approach and Philosophy of On baking technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
cuic standard and advanced reporting.pdf
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
PDF
Modernizing your data center with Dell and AMD
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPT
Teaching material agriculture food technology
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Approach and Philosophy of On baking technology
Network Security Unit 5.pdf for BCA BBA.
Chapter 3 Spatial Domain Image Processing.pdf
Electronic commerce courselecture one. Pdf
cuic standard and advanced reporting.pdf
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
Understanding_Digital_Forensics_Presentation.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
Modernizing your data center with Dell and AMD
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Teaching material agriculture food technology
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Spectral efficient network and resource selection model in 5G networks
MYSQL Presentation for SQL database connectivity
Unlocking AI with Model Context Protocol (MCP)
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Diabetes mellitus diagnosis method based random forest with bat algorithm
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

Lecture 5 numbers and built in functions