Chp-3: Numbers#
Chapter Objectives
By the end of this chapter, the student should be able to:
Define the various numeric data types supported in Python.
Perform basic arithmetic operations in Python.
Perform operations using Python’s precedence rules.
Apply conversion functions between different numeric data types in Python.
Use built-in mathematical functions and constants available in Python’s math module.
Solve real-world problems using variables.
Number Types#
In this chapter, three different types of numbers in Python will be covered, but integers and floats will be the primary types used in this book. If the sections on Floats, Complex Numbers, and Scientific Notation seem too technical for you, feel free to skip them.
Integers: …,-2,-1,0,1,2,…
Type: int
In Python, underscores (rather than commas) are used to separate large numbers into groups of three digits.
Float : 4.5, 3.0
Decimal numbers (They have decimal point).
4.0 is a float
Type: float
Float values are approximately stored, but they are close enough to their real values to maintain practical accuracy.
Complex Numbers: \(3+4j\)
Real numbers with imaginary parts.
In mathematics, the symbol \(i\) is used to represent the imaginary unit.
In Python, the symbol \(j\) is used to represent the imaginary unit.
The built-in
complex()
function is used to create complex numbers.Type: complex
# type of 5 is integer
print(type(5))
<class 'int'>
# type of -5 is integer
print(type(-5))
<class 'int'>
# type of 12.89 is float
print(type(12.89))
<class 'float'>
# type of 4.0 is float
print(type(4.0))
<class 'float'>
Floats#
Python does not store the value 0.1 exactly.
The following code reveals that there are non-zero numbers in the decimal tail, which are not expected to be there.
The built-in
format()
function can be used to display more decimal places.
# 30 digits after decimal point
print(format(0.1, '.30f'))
0.100000000000000005551115123126
0.5 is stored exactly in Python.
# 30 digits after decimal point
print(format(0.5, '.30f'))
0.500000000000000000000000000000
0.375 is stored exactly in Python.
# 30 digits after decimal point
print(format(0.375, '.30f'))
0.375000000000000000000000000000
This is because numbers, even decimal ones, are stored in base two.
If you can represent a decimal number in base two, it will be stored exactly.
However, some numbers, like 0.1, cannot be accurately represented in base two.
Examples
If you try to write the 0.375 in base two, you get:
\(0.375=\frac{3}{8}=\frac{1}{4}+\frac{1}{8}\)
Hence \(0.375\) in base two is \(0.011\) and stored exactly.
If you attempt a similar computation for 0.1, you will encounter an infinite series.
\(0.1 = \frac{1}{16}+\frac{1}{32}+\frac{1}{256}+\frac{1}{512}+... \)
Hence \(0.1\) is \(0.000110011...\) in base two.
Quick Check!
Display the first 20 decimal places of the number 1.235
Are there any unexpected decimal values?
Solution
print(format(1.235, '.20f'))
Complex Numbers#
Use the built-in
complex()
function to create complex numbers.It takes two parameters: the real part and the imaginary part.
With complex numbers, you can perform algebraic operations and find conjugates.
# real part = 2, imaginary part = 3
print(complex(2,3))
(2+3j)
z = complex(2,3)
# real part of z
print(z.real)
2.0
# imaginary part of z
print(z.imag)
3.0
# conjugate of z
print(z.conjugate())
(2-3j)
t = complex(5,7)
print(t)
(5+7j)
# addition
print(z + t)
(7+10j)
# subtraction
print(z-t)
(-3-4j)
Quick Check!
Create a variable whose value is the complex number \(4+5j\) and check its type.
Solution
z = complex(4,5)
print(type(z))
Scientific Notation#
It is used to represent very large or very small numbers in a more compact form.
In scientific notation, a number is written in the form of:
(a number between 1 and 10) x e(a power of 10)
Example: \(12345 = 1.2345 \times 10^{4} = 1.2345e+04\)
Example: \(0.00123 = 1.23 \times 10^{-3} = 1.23e-03\)
In scientific notation,
e+04 means \(10^4\)
e-03 means \(10^{-3}\)
Instead of e, you can also use E for scientific notation.
The
format()
function can be used to represent a number using scientific notation.
# Scientific notation e
# The number 3 represents the number of digits up to which the given number is to be rounded."
print(format(12645, '10.3e'))
1.264e+04
# round 1.2645 to the nearest tenth
print(format(12645, '10.1e'))
1.3e+04
# You can also use E instead of e
print(format(12645, '10.1E'))
1.3E+04
Large Numbers#
\(1,234,578\) is a large number, and commas are used to facilitate a better understanding of this number.
In Python, underscores (_) are used instead of commas due to the special functionalities associated with commas in Python.
print(1_234_578)
1234578
In the following code, comma-separated three values are printed.
Since the sep parameter is by default one space, these three values are displayed with one space between them.
print(1,234,578)
1 234 578
Operations on numbers#
The following operations are commonly used in Python:
Symbol |
Operation |
---|---|
\(+\) |
addition |
\(-\) |
subtraction |
\(*\) |
multiplication |
\(**\) |
exponent |
\(/\) |
division |
\(//\) |
divide and floor (integer division) |
\(\%\) |
remainder |
Division in Python always returns a float, even in cases where the result is a whole number.
12/4 = 3.0
Integer division rounds down to the nearest smaller integer.
Example:
13/5 = 2.6
13//5 = 2
Example:
-12/5 = -2.4
-12//5 = -3
The remainder operation
%
returns the remainder of a division.Example:
When we divide 13 by 5, the quotient is 2, and the remainder is 3.
13%5=3
# addition
print(5+3)
8
# subtraction
print(5-3)
2
# multiplication
print(5*3)
15
# division
print(13/5)
2.6
# exponent
# 2 to the third power
print(2**3)
8
# integer division
print(13//5)
2
# remainder
# when we divide 13 by 5, the remainder is 3.
print(13%5)
3
# power = 1/2 means square root
print(49**(1/2))
7.0
# square root of negative numbers are complex numbers.
# square root of -1
print((-1)**(1/2))
(6.123233995736766e-17+1j)
In the code above we expect to have only \(1j\) which is \(j\).
There is a real part in this complex number, which is supposed to be 0.
The real part \(6.123233995736766e-17\) is in scientific notation, representing \(6.123233995736766\times 10^{-17}\)
This is a very small number close to 0.
We have this small number as the real part because floats are stored approximately.
Quick Check!
Divide 18 by 3, assign the result to a variable named x, and then check the type of x to determine its data type.
Solution
x = 18/3
print(type(x))
Conversions#
The built-in
int()
function is used to convert floats and suitable strings to integers.The built-in
float()
function is used to convert integers and suitable strings to floats.The built-in
str()
function is used to convert integers and floats to strings.
# convert positive float x to integer y
x = 7.56
y = int(x)
print('Type:', type(y))
print('y =', y)
Type: <class 'int'>
y = 7
# convert negative float x to integer y
x = -7.56
y = int(x)
print('Type:', type(y))
print('y =', y)
Type: <class 'int'>
y = -7
# convert string x to integer
x = '7'
y = int(x)
print('Type:', type(y))
print('y =', y)
Type: <class 'int'>
y = 7
# ERROR: 'Tom' cannot be converted to an integer.
int('Tom')
# convert integer x to float y
x = 7
y = float(x)
print('Type:', type(y))
print('y =', y)
Type: <class 'float'>
y = 7.0
# convert string x to float y
x = '7.53'
y = float(x)
print('Type:', type(y))
print('y =', y)
Type: <class 'float'>
y = 7.53
You cannot convert decimal numbers in string type to an integer.
# ERROR: string '7.63' cannot be converted to an integer.
int('7.53')
Extra spaces on the left or right do not affect the conversion process.
print(int(' 234 '))
234
Quick Check!
In a single line of code, convert ‘3’ to a float number then integer and check its type.
Solution
print(type(int(float('3'))))
Precedence (PEMDAS)#
The operation precedence of the operations in Python follows the following order:
Parenthesis
Exponents
Multiplication, Division, Integer Division, Remainder
Addition, Subtraction
# first multiplication, then addition
print(2+5*3)
17
# first remainder, then addition
print(2+5%3)
4
# first Integer Division, then addition
print(2+5//3)
3
# first exponent, then addition
print(2+5**3)
127
Quick Check!
Given the variable x=3
, evaluate the expression 4+2(x+5)-3x
Solution
x = 3
print(4+2*(x+5)-3*x)
Abbreviated operators#
In mathematics, the expression \(x=x+1\) represents an equation. By subtracting \(x\) from both sides, the equation can be solved.
In programming languages, \(x=x+1\) is an assignment, not an equation. Remember that
=
is an assignment operator.In the assignment \(x=x+1\), the following steps occur:
The expression on the right-hand side, \(x+1\), is computed first using the current value of \(x\).
The result becomes the new value of \(x\).
x = 3 # value of x is 3
x = x+1 # x = 3+1
print(x)
4
x = 25 # value of x is 25
x = x-3 # x = 25-3
print(x)
22
x = 10 # value of x is 10
x = x*2 # x = 10*2
print(x)
20
x = 15 # value of x is 15
x = x/3 # x = 15/3
print(x)
5.0
Since these types of assignments are used frequently, there is a shorter version for them.
regular |
shorter |
---|---|
x = x+2 |
x+=2 |
x = x-2 |
x-=2 |
x = x*2 |
x*=2 |
x = x/2 |
x/=2 |
x=3 # value of x is 3
x += 1 # x = 3+1
print(x)
4
x = 25 # value of x is 25
x -= 3 # x = 25-3
print(x)
22
x = 10 # value of x is 10
x *= 2 # x = 10*2
print(x)
20
x = 15 # value of x is 15
x /= 3 # x = 15/3
print(x)
5.0
Quick Check!
Find the output of the following code.
a = 10
a += 2
print(a)
a /= 3
print(a)
a *= 5
print(a)
Solution
12
4.0
20.0
Built-in Functions#
Python has many useful functions available for use without importing additional modules.
You can find the list of built-in functions in the official Python documentation.
Some of the built-in functions related to mathematics include:
abs()
: returns the absolute value.max()
: returns the maximum value in a given list of numbers.min()
: returns the minimum value in a given list of numbers.sum()
: returns the sum of the values in a given list of numbers.pow()
: returns a number (base) raised to a certain power.round()
: rounds a number to a certain decimal place.
# absolute values of -7
print(abs(-7))
7
# maximum of 1,9,2,4 is 9
print(max(1,9,2,4))
9
# minimum of 1,9,2,4 is 1
print(min(1,9,2,4))
1
# sum of 1,9,2,4 is 16
# numbers in square brackets or parenthesis
print(sum([1,9,2,4]))
16
# 2 to the 3rd power
print(pow(2, 3))
8
# rounding to the nearest thousandths
print(round(3.4678, 3))
3.468
Quick Check!
Create three variables, x, y, and z, and assign them the values -2, -5, and -10, respectively.
Use the
min()
function to find and display the minimum of these numbers.Use the
abs()
function to get the absolute values of x, y, and z, then display their sum.
Solution
x, y, z = -2, -5, -10
print('Minimum:', min(x,y,z))
print('Sum :', sum([abs(x),abs(y),abs(z)]))
Math Module#
Modules will be imported as needed, not loaded by default.
This minimizes memory requirements and improves performance.
Modules are single Python files with a .py extension, which may contain functions and constants.
The Math module contains commonly used mathematical functions and constants, including trigonometric functions and the constant \(\pi\).
The math module should be imported first.
dir(math)
returns a list of all functions and constants in the math module.help(math)
provides more details, including explanations of functions and constants.You do not need to memorize these functions. Whenever you need any of them, you can import them from the module.
import math
# list of constants and functions in math module
print(dir(math))
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
# sin(30 radians)
math.sin(30)
-0.9880316240928618
# square root
math.sqrt(49)
7.0
# converts degrees to radians
math.radians(180)
3.141592653589793
# log of 100 in base 10
math.log10(100)
2.0
Quick Check!
Create a variable named radius
and assign it the value 5. Import the value of \(\pi\) from the math
module. Then, use the formula \(A = \pi r^2 \) to calculate the area of the circle. Finally, round the result to the nearest hundredth.
Solution
import math
radius = 5
A = round(math.pi*radius**2,2)
print('Area:', A)
Combine Strings and Numbers#
There are different ways of combining strings and numbers.
One easy way is to convert numbers to a string using the str() function and then concatenate strings using the + operator.
x = 5
y = 'dollars'
# ERROR: int + str
print(x+y)
# convert x into a string: new value is '5'
# concatenate three strings: str(x), ' ', y
new_str = str(x)+' '+y
print(new_str)
5 dollars
Quick Check!
Use string concatenation by converting the variable x = 5
to a string and then concatenate it with the variable y = '7'
. Assign the result to a new variable, which will hold the string value '75'
.
Solution
x = 5
y = '7'
z= y+str(x)
print(z)