Author: Ken Levasseur
Description: Worksheets related to Applied Discrete Structures

# An Introduction to Functions using Sage

This document describes the basic ways in which a function can be represented with Sage.  These topics are introduced in chapter 7 of Applied Discrete Structures.

In any computer program a function defined by a piece of code that will accept inputs and produce outputs. This is a bit more general than the mathematical concept of a function, but close enough to let use study the concept through programming. The function on the set $\{0,1,2,3,4,5,6\}$ defined by the ordered pairs $\{(0,0), (1,1), (2,4), (3,2), (4,2),(5,4), (6,1)\}$ can be represented as a dictionary:

def f(x):
return {0:0,1:1,2:4,3:2,4:2,5:4,6:1}[x]

f(4)

2

Not every function can be easily defined by a formula, but this one can be using the standard synatax for Python/SageMath functions.

def f(x):
return x^2 %7

f(4)

2
%html
<p>
Not every SageMath function is a true function.  For example, if the output is governed by a random number generator, the output for a given input will vary.  Here is a function that returns 1 with probability $p$ and 0 with probability $1-p$.
</p>


Not every SageMath function is a true function. For example, if the output is governed by a random number generator, the output for a given input will vary. Here is a function that returns 1 with probability $p$ and 0 with probability $1-p$.

def nonfunction(p):
if random()<p:
return 1
else:
return 0

outputs=[]
for k in range(10):
outputs=outputs+[nonfunction(0.3)]
outputs

[0, 0, 1, 1, 1, 0, 0, 1, 0, 0]