A function gives exactly one output for each input. Functions model programs, formulas and mappings, and some special functions appear constantly in computer science.

Definition

A function f from A to B (written f: A → B) assigns to every element x of A exactly one element f(x) of B. A is the domain, B is the codomain, and the set of values actually produced is the range. For f(x) = x² on integers, the range is the perfect squares.

Types of functions

  • Injective (one-to-one): different inputs give different outputs. f(x) = 2x + 1 is injective.
  • Surjective (onto): every element of the codomain is hit. f(x) = x³ on real numbers is onto.
  • Bijective: both injective and surjective. A bijection pairs elements of two sets perfectly.
f: R → R Injective Surjective
f(x) = x² No (2 and −2 give 4) No (no negative outputs)
f(x) = 2x + 1 Yes Yes (so bijective)

Composition and inverse

The composition (f ∘ g)(x) = f(g(x)): apply g first, then f. If f(x) = x + 1 and g(x) = 2x, then (f ∘ g)(x) = 2x + 1 and (g ∘ f)(x) = 2x + 2. Composition is generally not commutative.

The inverse f⁻¹ exists only when f is bijective, and it undoes f. For f(x) = 2x + 1, solve y = 2x + 1 for x to get f⁻¹(y) = (y − 1) / 2.

Functions useful in computer science

  • Exponential f(x) = aˣ grows very fast. Doubling each step gives 2ⁿ.
  • Logarithmic log₂ n is the inverse of 2ⁿ. It counts how many times n can be halved, which is why binary search takes about log₂ n steps. log₂ 8 = 3.
  • Polynomial f(n) = aₖnᵏ + ... + a₀, such as 3n² + 2n + 1, used to describe running times.
  • Floor ⌊x⌋ is the greatest integer not above x: ⌊3.7⌋ = 3, ⌊−2.5⌋ = −3.
  • Ceiling ⌈x⌉ is the least integer not below x: ⌈3.2⌉ = 4, ⌈−2.5⌉ = −2.

Use of ceiling: 100 items packed 30 per box need ⌈100 / 30⌉ = 4 boxes.

Worked example

Show f(x) = 3x − 2 is a bijection on the real numbers and find f⁻¹. If 3a − 2 = 3b − 2 then a = b, so f is injective. For any y, x = (y + 2)/3 gives f(x) = y, so f is onto. Hence f⁻¹(y) = (y + 2) / 3.

Common mistakes

  • Calling a relation a function when one input has two outputs.
  • Taking the inverse of a function that is not bijective.
  • Rounding negative numbers towards zero when asked for the floor.

Practice questions

  1. Define function, domain, codomain and range.
  2. Is f(x) = x² on the integers injective? Is it onto the integers?
  3. If f(x) = 3x and g(x) = x + 2, find f ∘ g and g ∘ f.
  4. Find ⌊−1.2⌋, ⌈−1.2⌉, ⌊5⌋ and ⌈5.01⌉.
  5. Find the inverse of f(x) = 5x − 3.

Answers to the practice questions

  1. See the definition above.
  2. Not injective (f(2) = f(−2) = 4); not onto (2 is not a square).
  3. (f ∘ g)(x) = 3x + 6 and (g ∘ f)(x) = 3x + 2.
  4. −2, −1, 5 and 6.
  5. f⁻¹(y) = (y + 3) / 5.

Sources

  • Official BCA syllabus Mathematics Foundations to Computer Science I, course code CC101, Unit I
  • Kolman, Busby and Ross, Discrete Mathematical Structures, 6th edition, Pearson