Function and Algorithms (Chapter3)
Function and Algorithms (Chapter3)
Chapter 3
Functions and Algorithms
Function: Definition
A function f from X to Y (in
symbols f : X → Y) is a relation
from X to Y such that Dom(f) = X
and if two pairs (x,y) and (x,y’) ∈ f,
then y = y’
Example:
Dom(f) = X = {a, b, c, d},
Range(f) = {1, 3, 5}
f(a) = f(b) = 3, f(c) = 5, f(d) = 1.
Domain and Range
Domain of f = X
Range of f =
{ y | y = f(x) for some x ∈X}
A function f : X → Y assigns to
each x in Dom(f) = X a unique
element y in Range(f) ⊆ Y.
Therefore, no two pairs in f have
the same first coordinate.
f: R→R, f (x) = x 2
x x2
f
f(-3) =9 9 is the Image of -3
f(√2) = 2 Some elements of the
codomain are not images of
f(5) = 25 the elements of the domain.
E.g. -1 is an element of the
codomain but is never used.
The range is a subset of the
codomain.
Examples
1. Let A = {1, 2, 3} and B = {1, 2, 3, 4}. Let f be
the function defined in the following way:
f: A→B, f(1) = 3, f(2) = 2, f(3) = 2
Domain = A ={1 , 2, 3}
Codomain = B = { 1, 2, 3, 4}
Range = subset of B = { 2, 3}
Hash Function
Suppose That we have cells in computer
memory indexed from 0 to 10. We wish to
store and retrieval integers in these cells.
Format of Hash function is H(n) = n mod (m)
where m is the number of available memory
locations.
Here m = 11
Input Index
Hash Function: H(n)
Integer
Hash Function
132 102 15 5 32
0 1 2 3 4 5 6 7 8 9 10
Retrieve
n= 102 Index=3
H(n)= n mod 11
Store
n= 257 Index=4
H(n)= n mod 11
One-to-one functions
A function is one-to-one if no two distinct elements of
the domain have the same image.
A function f : X → Y is one-to-one ⇔ for each
y ∈ Y there exists at most one x ∈ X with f(x) = y.
One-to-one= Injective
Onto functions
A function is onto if its range is equal to its
codomain
A function f : X → Y is onto ⇔ for each y ∈ Y there
exists at least one x ∈ X with f(x) = y, i.e. Range(f) = Y.
Onto function = Surjective
Example: The function f(x) = ex from the set of real
numbers to itself is not onto, where
Y = the set of all real numbers.
However, if Y is restricted to Range(f) = R +, the set of
positive real numbers, then f(x) is onto.
Bijective functions
A function f : X→ Y is bijective ⇔
f is one-to-one and
onto
Examples:
1. A linear function f(x) = ax + b is a bijective
(C) (D)
(E)
A B C
g f
g(a) f(a)
a f(g(a))
g(a)
(f ○ g)(a)
Compositions of functions
Let f(x) = 2x+3 f○g
Let g(x) = 3x+2
R R R
g f
g(1) f(5)
f(g(1))=13
1
g(1)=5
(f ○ g)(1)
3(x2 - 1 )+5
f g: x x -1
2
g f
x 3x +5 (3x+5)2 - 1
g f: f g
Exponential and
logarithmic functions
Let f(x) = 2x and g(x) = log 2 x = lg x