Piecewise Functions and Conditionals
@BootstrapWorld
Intro to Piecewise Functions
How would you explain a function to someone else? What are some rules that all functions follow?
Intro to Piecewise Functions
Today we are going to act out a special kind of function.
What is the input of the function we just acted out? The output? How do we know that you just acted out a function?
Intro to Piecewise Functions
Up until now, all of the functions we have seen can be described by a single rule.
In this activity your behavior followed a set of rules for which each input still had exactly one output.
This is called a piecewise function in math, and a conditional in programming. The world is full of piecewise functions and conditionals!
Intro to Piecewise Functions
Let's try acting out another set of rules.
Why doesn't this set of directions represent a function?
Intro to Piecewise Functions
Work with your partner to think of real-world examples of piecewise functions.
Then, we'll share out what we came up with.
Conditionals in Programming
The rule for gt was to take a number and make a solid, green triangle of that size. The rule for bc was to take a number and make a solid, blue circle of that size.
What if we want to write functions that apply different rules, based on certain conditions?
Conditionals in Programming
Conditionals in Programming
What happened when you gave red-shape a shape that wasn't defined in the program?
What is the syntax for writing piecewise functions?
Extending the Design Recipe
Let's see how the Design Recipe could help us to write a piecewise function.
Extending the Design Recipe
If there are more unique labels in the examples than there are things in the Domain, we're probably looking at a piecewise function.
Think back to our examples of piecewise functions (ticket sales, postage, cell-phone data plans, etc): knowing the input isn't enough - we also need to know the conditions!
Extending the Design Recipe
In this example, we have four totally different patterns:
Extending the Design Recipe
To define a piecewise function, each condition has both a result ("what should we do") and a question ("when should we do it?").
Extending the Design Recipe
Adding the questions to our pattern gives us:
Extending the Design Recipe
This practically gives away the body of our function definition!
Extending the Design Recipe
Additional Practice