<jupyter_start><jupyter_text>Learning ObjectivesIn this section, you will:* Determine whether a relation represents a function.* Find the value of a function.* Determine whether a function is one-to-one.* Use the vertical line test to identify functions.* Graph the functions listed in the library of functions.  Use this [Link](https://www.youtube.com/watch?v=RTpL1lPmlls&list=PLx8hCMnrVJFP0bkd8gpImKdLOffwVjhgk&index=11) for videos on finding the factors of binomials and trinomials  Determining Whether a Relation Represents a FunctionA relation is a set of ordered pairs. The set of the first components of each ordered pair is called the **domain** and the set of the second components of each ordered pair is called the **range**.A function $f$ is a relation that assigns a single value in the *range* to each value in the *domain*. In other words, given values in the domain as $x$ and those in the range as $y$, then for the relationship to be a function, no $x$-values are repeated, when assigning $y$ values to $x$ values.**This means that 2 distinct values in the domain may be assigned the same value in the range, but no two distinct values in the range can be assigned to the same value in the domain.**for example, if the domain contains amongst other values the values -2 and 2. Then both values may be assigned the same, single range value of 4, if the relationship between the domain and the range is a squaring relationship. I.e $2^2 = 4$ and $-2^2 = 4$Figure above: (a) This relationship is a function because each input is associated with a single output. Note that input  q  and  r  both give output  n.  (b) This relationship is also a function. In this case, each input is associated with a single output. (c) This relationship is not a function because input  q  is associated with two different outputs.  Relation Examples:Consider the following set of ordered pairs {$(1, 2), (2, 4), (3, 6), (4, 8), (5, 10)$}The domain is {$1, 2, 3, 4, 5$} and the range is {$2, 4, 6, 8, 10$}.Since each distinct value in the domain is assigned only one value in the range, this relation is a Function. Now, consider the following...{$(odd, 1), (even, 2), (odd, 3), (even, 4), (odd, 5)$}Since each distinct value in the domain (odd, even) is assigned more than one value in the range (1, 3, 5) and (2, 4), this relation is not a Function. Note that each value in the domain is also known as an _input value_, or _independent variable_, and is often labeled with the lowercase letter  $x$.  Each value in the range is also known as an _output value_, or _dependent variable_, and is often labeled lowercase letter  $y$.  HOW TO IDENTIFY A FUNCTION FROM A RELATION:Given a relationship between two quantities, determine whether the relationship is a function.1. Identify the input values.2. Identify the output values.If each input value leads to only one output value, classify the relationship as a function. If any input value leads to two or more outputs, do not classify the relationship as a function.  FUNCTIONA function is a relation in which each possible input value leads to exactly one output value. **We say “the output is a function of the input.”** The input values make up the **domain**, and the output values make up the **range**.* Is price a function of the item?* Is the item a function of the price?I say the price is a function of the item, since each item has just one price... But, the item is not a function of the price, since the same price of $1.99 has different items. **Ex 2.**I'd say Percent-Range(PR or PG) is a function of Grade-Point-Average(GPA), since each GPA has just one PG score.While, GPA is not a function of PG, since each PG has multiple or a range of GPA scores. **Ex 3.**Yes the rank is a function of player name, given that each player name produces a specific rankAlso, the player name is a function of the rank, given that each rank produces a specific player name.  FUNCTION NOTATIONThe notation  $y=f(x)$  defines a function named  $f$.  This is read as  “$y$  is a function of  $x$.”  The letter  $x$  represents the _input value_, or _independent variable_. The letter  $y$,   or  $f(x)$,  represents the _output value_, or _dependent variable_. **Using Function Notation for Days in a Month**Use function notation to represent a function whose input takes two values:- The name of a month and the year in question. Then it outputs the number of days in that month. Let's denote some variables...* $d$ = number of days in a month. This is our dependent variable or $y$* $x$ = (name-of-the-month, year-in-question). These are our independent variablestherefore $d = f(x)$where $f$ is a function that takes $x$ and outputs $d$<jupyter_code>import pandas as pd
import numpy as np
from calendar import monthrange
import matplotlib.pyplot as plt
def days_in_month(month, year=2021):
    """Function takes a month and
        returns the number of days
    
    @param month: string, for name of month
    @param year: int, default 2021, can be any legal year
    @return: int, number of days in month
    """
    month = month[:3].lower()
    
    temp = {'jan':1, 'feb':2, 'mar':3, 'apr':4, 'may':5, 'jun':6,
           'jul':7, 'aug':8, 'sep':9, 'oct':10, 'nov':11, 'dec':12}
    
    month_id = temp[month]
    num_days = monthrange(year, month_id)[1]
    
    return num_days
# Check number of days in Feb 2021

month = 'February'
days_in_month(month)
# Check number of days in Feb 2016, a leap-year

year = 2016
days_in_month(month, year)
# Check number of days in Dec 1959

year = 1959
month = 'december'
days_in_month(month, year)<jupyter_output><empty_output><jupyter_text>**Solution**The number of days in a month is a function of the name of the month, so if we name the function $f$, we write  $days=f(month)$  or $d=f(m)$. The name of the month is the input to a **“rule”** that associates a specific number (the output) with each input.For example, $f(March)=31$, because March has 31 days. The notation $d=f(m)$ reminds us that the number of days, $d$ (the output), is dependent on the name of the month, $m$ (the input)._Analysis_Note that the inputs to a function do not have to be numbers; function inputs can be names of people, labels of geometric objects, or any other element that determines some kind of output. However, most of the functions we will work will have numbers as inputs and outputs. **Interpreting Function Notation:**A function $N=f(y)$ gives the number of police officers, $N$, in a town in year $y$. What does $f(2005)=300$ represent?It represents the functional expression that for the year 2005, there are 300 police officers in the town **Ex 4:**Use function notation to express the weight of a pig in pounds as a function of its age in days $d$.$f(d) = w$, where $d$ = age-in-days and $w$ = weight-in-pounds  Q&AInstead of a notation such as $y=f(x)$, could we use the same symbol for the output as for the function, such as $y=y(x)$,  meaning **“y is a function of x?”**Yes, this is often done, especially in applied subjects that use higher math, such as physics and engineering. However, in exploring math itself we like to maintain a distinction between a function such as $f$, which is a rule or procedure, and the output $y$ we get by applying $f$ to a particular input $x$. This is why we usually use notation such as $y=f(x)$, $P=W(d)$,  and so on.  Finding Input and Output Values of a Function:When we know an input value and want to determine the corresponding output value for a function, we evaluate the function. Evaluating will always produce one result because each input value of a function corresponds to exactly one output value.**When we know an output value and want to determine the input values that would produce that output value, we set the output equal to the function’s rule or formula and solve for the input.** Solving can produce more than one solution because different input values can produce the same output value.  Evaluation of Functions in Algebraic Forms:When we have a function in formula form, it is usually a simple matter to evaluate the function. For example, the function  $f(x)=5−3x^2$ can be evaluated by squaring the input value, multiplying by 3, and then subtracting the product from 5.This simply means for any value of $x$, $f(x)$ is 5-($x^2$*3) **EXAMPLE 6:**Evaluating Functions at Specific ValuesEvaluate  $f(x)=x^2+3x−4$  at:* 2* a* a+h<jupyter_code># when x is 2
x = 2

f_of_x = x**2+3*x-4
f_of_x<jupyter_output><empty_output><jupyter_text>when x = a**f_of_x = $a^2 + 3a - 4$** when x = a+hf_of_x = $(a+h)^2 + 3(a+h) - 4$**f_of_x = $a^2 + 2ah + h^2 + 3a + 3h - 4$** Now evaluate   ${f(a+h)−f(a)} \over h$ From the above, since we know what $f(a+h)$ and $f(a)$ are, we can substitute these values to the numerator above x = ${(a^2 + 2ah + h^2 + 3a + 3h - 4) - (a^2 + 3a - 4)} \over h$Now expand the parenthesis... x = ${a^2 + 2ah + h^2 + 3a + 3h - 4 - a^2 - 3a + 4} \over h$ Now, we solve for like terms x = ${2ah + h^2 + 3h} \over h$ Now, we continue, solving for $h$ in denominator x = ${h(2a + h + 3)} \over h$X is now: x = $2a + h + 3$ **Evaluating Functions**Given the function   $h(p)=p^2+2p$evaluate $h(4)$.<jupyter_code>p = 4

h_of_p = p**2 + 2*p
h_of_p<jupyter_output><empty_output><jupyter_text>Therefore, for an input of 4, we have an output of 24. Given the function   $g(m)= \sqrt{m-4}$  evaluate g(5).<jupyter_code>m = 5

g_of_m = (m - 4)**0.5
g_of_m<jupyter_output><empty_output><jupyter_text>Given the function   $h(p)=p^2+2p$solve for $h(p)=3$. **Let's solve the above function manually...** $h(p) = p^2 + 2p$ solve for $h(p) = 3$ Solving this means that $3 = p^2 + 2p$, which is same as $p^2 + 2p = 3$Now, let's deduct 3 from both sides of the equation $p^2 + 2p - 3 = 0$Now, for the given trinomial above, let's factor it into 2 binomials.The first values will be $p$ and $p$ to create the first term $p^2$ $(p )(p )$Since the trinomial has a leading coefficient of 1 ($1 * p^2$), to find the remaining values,We need to find two numbers whose product is -3 and whose sum is 2...This gives us the numbers 3 and -1 $(p + 3)(p - 1)=0$To check if we got the factors right, we can multiply using **FOIL****F**: First**O**: Outer**I**: Inner**L**: lastThus $(p*p) + (p*-1) + (3*p) + (3*-1)$This gives $p^2 - p + 3p - 3$Which evaluates to the original trinomial $p^2 + 2p -3$ Going by the two factors above, it means that either $(p + 3) = 0$ or $(p - 1) = 0$ or both.This means that when the output ($h(p) = 3$), then the inputs are either $p$ = -3 or $p$ = 1  Graphing the above function to show the inputs for $h(p) = 3$<jupyter_code># Lets take a range of input values p from -5 to 5
p_range = list(range(-5,6))
# now a function to find h-of-p, given p-range

def h_of_p(p_range):
    hOfP = [p**2 + 2*p for p in p_range]
    
    return hOfP
print(p_range)
h_of_p(p_range)
def values_to_df(function_output, *args, columns=['Output']):
    p_values = pd.DataFrame(function_output(*args), index=args[0], columns=['Output'])
    p_values.index.name = 'Input'
    
    return p_values
p_values = values_to_df(h_of_p, p_range, columns=['Output'])
p_values
p_values.plot(grid=True)
plt.annotate(xy=(-3, 3), text='*', color='r')
plt.annotate(xy=(1, 3), text='*', color='r')
plt.title('function to plot h(p)=3, given, h(p)=p^2 + 2p')
plt.show()<jupyter_output><empty_output><jupyter_text>**We can see the red dots for both inputs -3 and 1 having the same output of 3**  Given the function   $g(m)=\sqrt{m-4}$,  **solve $g(m)=2$**. * This also means...=> $\sqrt{m-4}=2$,* To remove the sqrt, we square the value...=> $m-4=2^2$, which is $m-4=4$* Now we solve for $m$...=> $m=4+4$, $m=8$This means that the function $g(m)=2$, when $m=8$. Only 8 can satisfy the rule in this case... Let's graph it<jupyter_code># Lets take a range of input values p from -4 to 5
p_range = list(range(4,13))

# let's define the function rule/formula
def g_of_m(p_range):
    r_values = [np.round((m-4)**0.5,2) for m in p_range]
    
    return r_values
# Let's see the domain and range values
print(p_range)
g_of_m(p_range)
p_values = values_to_df(g_of_m, p_range, columns=['Output'])
p_values.plot(grid=True)
plt.annotate(xy=(8, 2), text='*', color='r')
plt.title('function to plot g(m)=2, given, g(m)=sqrt{m-4}')
plt.show()<jupyter_output><empty_output><jupyter_text>Evaluating Functions Expressed in FormulasSome functions are defined by mathematical rules or procedures expressed in equation form. If it is possible to express the function output with a formula involving the input quantity, then we can define a function in algebraic form. For example, the equation  $2n+6p=12$  expresses a functional relationship between  $n$  and  $p$.  We can rewrite it to decide if  $p$  is a function of  $n$.**HOW TO**_Given a function in equation form, write its algebraic formula._1. Solve the equation to isolate the output variable on one side of the equal sign, with the other side as an expression that involves only the input variable.2. Use all the usual algebraic methods for solving equations, such as adding or subtracting the same quantity to or from both sides, or multiplying or dividing both sides of the equation by the same quantity. _Finding an Equation of a Function_Express the relationship $2n+6p=12$ as a function $p=f( n )$, if possible. 1. Isolate $p$ by subtracting $2n$ from both sides...=> $6p=12-2n$,2. Now divide both sides by 6 to further isolate $p$...=> $p=(\frac{12}{6})-(\frac{2n}{6})$3. finally...=> $p=f(n)=>2-\frac{2n}{6}$So whatever value $n$ is, $p$ is a function of $n$ based on the rule that $2-\frac{2n}{6}=p$  Evaluating a Function Given in Tabular FormAs we saw above, we can represent functions in tables. Conversely, we can use information in tables to write functions, and we can evaluate functions using the tables.<jupyter_code>n = [1,2,3,4,5]
gn = [8,6,7,6,8]

tab1 = pd.DataFrame([n, gn], index=['n', 'g(n)'], columns='A B C D E'.split())
tab1<jupyter_output><empty_output><jupyter_text>**Using tab1 above, evaluate**ⓐ Evaluate $g( 3 )$.ⓑ Solve $g( n )=6$.From tab1 we can see that...* $g(3)=7$ cos when $n$ is 3, $g(n)$ is 7* And when $g(n)=6$ we can also see that the input values for $n$ are $n=(2,4)$  Finding Function Values from a GraphEvaluating a function using a graph also requires finding the corresponding output value for a given input value, only in this case, we find the output value by looking at the graph. Solving a function equation using a graph requires finding all instances of the given output value on the graph and observing the corresponding input value(s).<jupyter_code>x = list(np.arange(-4, 4.05, 0.5))
y = [i**2 for i in x]
pd.DataFrame([x, y]).T.set_index(0).plot()
plt.title('Plot for f(x) = x^2')
plt.grid()
plt.ylabel('y', fontweight='bold')
plt.xlabel('X', fontweight='bold')
plt.show()<jupyter_output><empty_output><jupyter_text>The above graph represents the function $f(x) = x^2$from the graph, evaluate:ⓐ $f( 1 )$.ⓑ Solve $f( x )=4$.From the graph, we can see that when $x=1$, $y=1$ too thus $f(1)=1$We can also see that when $f(x)=4$ meaning when $y=4$, solving it means finding the$x$'s that satisfy it and these are $\approx$$(-2,2)$* $f(x) = 4$* $4 = f(x)$* $4 = x^2$* $x^2 = 4$* $x = \sqrt{4}$* $x=\pm{2}$  Determining Whether a Function is One-to-One:Some functions have a given output value that corresponds to two or more input values. However, some functions have only one input value for each output value, as well as having only one output for each input. We call these functions **one-to-one** functions. To visualize this concept, let’s look again at the two simple functions sketched below. The function in part (a) shows a relationship that is not a one-to-one function because inputs  $q$  and  $r$  both give output  $n$.  The function in part (b) shows a relationship that is a one-to-one function because each input is associated with a single output. ONE-TO-ONE FUNCTION_A one-to-one function is a function in which each output value corresponds to exactly one input value._* Is the area of a circle a function of its radius? * If yes, is the function one-to-one?The area $A = \pi{r}^2$, this means each radius $r$ produces a specific area $A$. Thus $A$ is a function of $r$.If the function is one-to-one, the output value $A$, must correspond to a unique input value $r$. Any area measure  $A$  is given by the formula  $A=\pi{r}^2$.  Because areas and radii are positive numbers (we can't have a negative radius), there is exactly one solution:  $r=\sqrt{\frac{A}{\pi}}$.  So the area of a circle is a one-to-one function of the circle’s radius. ⓐ Is a balance a function of the bank account number?ⓑ Is a bank account number a function of the balance?ⓒ Is a balance a one-to-one function of the bank account number? A. **Is a balance a function of the bank account number?**Let's write it down: Balance = $b$, Acct-number = $a$.. so is $b$ a function of $a$? as in... is $f(a)=b$Looking at a function definition, a unique value of $a$ can only produce one $b$, after the same rule in $f()$ has been applied to $a$ to check for $b$. So balance($b$) is a function of acct-number($a$), since calling a specific acct-number($a$) in a given function($f()$) that checks for it's balance($b$), will only produce one specific balance($b$) for each specific acct-number($a$). B. **Is a bank account number a function of the balance?**is $f(b)=a$? meaning is a specific balance($b$) going to produce only one account($a$) at all times that a function($f()$) is applied to $b$ while checking for $a$?Definitely not! Because a certain account-balance($b$) can be linked to multiple different bank-accounts($a$) across the globe. C. **Is a balance a one-to-one function of the bank account number?**in other words does $f(a)=b$ have a one-to-one relationship?If the function is _one-to-one_, then the output value $b$ will have only one distinct possible input value $a$, meaning for a given balance($b$), only one account($a$) can have $a$ balance, which is not so, clearly.  Evaluate the following:ⓐ If each percent grade earned in a course translates to one letter grade, is the letter grade a function of the percent grade?ⓑ If so, is the function one-to-one?Percent-Grade = $pg$Course = $c$Letter-Grade = $lg$ If each percent grade earned in a course translates to one letter grade, we know there are only 26 letters, it means that:* If each $pg$ is unique, then $lg=f(pg)$* If any $pg$ has more than one corresponding $lg$, then $lg\ne{f(pg)}$if $lg=f(pg)$, and total $pg$ <= 26, then $lg$ has a one-to-one relationship function with $pg$ otherwise not.  Using the Vertical Line Test:The **vertical line test** can be used to determine whether a graph represents a function. If we can draw any vertical line that intersects a graph more than once, then the graph does not define a function because a function has only one output value for each input value. **HOW TO**Given a graph, use the vertical line test to determine if the graph represents a function.* Inspect the graph to see if any vertical line drawn would intersect the curve more than once.* If there is any such line, determine that the graph does not represent a function.  Using the Horizontal Line TestOnce we have determined that a graph defines a function, an easy way to determine if it is a one-to-one function is to use the horizontal line test. Draw horizontal lines through the graph. If any horizontal line intersects the graph more than once, then the graph does not represent a one-to-one function.**HOW TO**Given a graph of a function, use the horizontal line test to determine if the graph represents a one-to-one function.* Inspect the graph to see if any horizontal line drawn would intersect the curve more than once.* If there is any such line, determine that the function is not one-to-one.  Graphing Popular Functions:  1. Constant Function: $f(x) = c$... where $c$ is some constant number<jupyter_code>def constant_(arr, c):
    """This function assigns all values
        of x, an output of c.
        
    @param c: a constant, number
    @param return: arr, a list, of all c
    """
    y = [c]*len(arr)
    return y
arr = x
c = 3

p_values = values_to_df(constant_, arr, c, columns=['Output'])
p_values.plot(grid=True)
plt.title(f'function to plot f(x)=c, where c is constant at {c}.')
plt.show()<jupyter_output><empty_output><jupyter_text>2. Identity Function: $f(x) = x$<jupyter_code>def identity_(arr):
    return arr
p_values = values_to_df(identity_, arr, columns=['Output'])
p_values.plot(grid=True)
plt.title(f'function to plot f(x)=x, The Identity Function.')
plt.show()<jupyter_output><empty_output><jupyter_text>3. Absolute-Value Function: $f(x) = |x|$<jupyter_code>def absolute_(arr):
    """For every value in arr,
        this function returns the 
        absolute value
    """
    y = [np.abs(i) for i in arr]
    return y
p_values = values_to_df(absolute_, arr, columns=['Output'])
p_values.plot(grid=True)
plt.title(f'function to plot f(x)=|x|, The Absolute Function.')
plt.show()<jupyter_output><empty_output><jupyter_text>4. Quadratic Function: $f(x) = x^2$<jupyter_code>def quadratic_(arr):
    """For every value in arr,
        return the value squared
    """
    y = [i**2 for i in arr]
    return y
p_values = values_to_df(quadratic_, arr, columns=['Output'])
p_values.plot(grid=True)
plt.title(f'function to plot f(x)=x^2, The Quadratic Function.')
plt.show()<jupyter_output><empty_output><jupyter_text>5. Cubic Function: $f(x) = x^3$<jupyter_code>def cubic_(arr):
    """For every value in arr,
        return the value cubed
    """
    y = [i**3 for i in arr]
    return y
p_values = values_to_df(cubic_, arr, columns=['Output'])
p_values.plot(grid=True)
plt.title(f'function to plot f(x)=x^3, The Cubic Function.')
plt.show()<jupyter_output><empty_output><jupyter_text>6. Reciprocal Function: $f(x) = \frac{1}{x}$<jupyter_code>def reciprocal_(arr):
    """For every value of arr,
        return the reciprocal value
    """
    y = [1/i if i != 0 else 0 for i in arr]
    return y
p_values = values_to_df(reciprocal_, arr, columns=['Output'])
p_values.plot(grid=True)
plt.title(f'function to plot f(x)=1/x, The Reciprocal Function.')
plt.show()<jupyter_output><empty_output><jupyter_text>7. Reciprocal Squared Function: $f(x) = \frac{1}{x^2}$<jupyter_code>def reciprocal_squ_(arr):
    """For every value of arr,
        return the reciprocal squared 
        value
    """
    y = [1/i**2 if i != 0 else 0 for i in arr]
    return y
p_values = values_to_df(reciprocal_squ_, arr, columns=['Output'])
p_values.plot(grid=True)
plt.title(f'Plotting f(x)=1/x^2, The Reciprocal-Squ\'d Function.')
plt.show()<jupyter_output><empty_output><jupyter_text>8. Square-Root Function: $f(x) = \sqrt{x}$<jupyter_code>def square_root_(arr):
    """For each value of arr,
        return the square-root
    """
    # since we can't find sqrt of negative numbers
    y = [np.sqrt(i) if i >= 0 else None for i in arr]
    return y
p_values = values_to_df(square_root_, arr, columns=['Output'])
p_values.plot(grid=True)
plt.title(f'Plotting f(x)=sqrt-of-x, The Square-Root Function.')
plt.show()<jupyter_output><empty_output><jupyter_text>8. Cube-Root Function: $f(x) = \sqrt[3]{x}$<jupyter_code>def cube_root_(arr):
    """For each value of arr,
        return the cube-root
    """
    y = [np.cbrt(i) for i in arr]
    return y
p_values = values_to_df(cube_root_, arr, columns=['Output'])
p_values.plot(grid=True)
plt.title(f'Plotting f(x)=cbrt-of-x, The Cube-Root Function.')
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11489668632525775, 'fraction_numerical': 0.016929016929016927, 'mean_word_length': 4.314543404735062, 'pattern_counts': {'":': 0, '<': 70, '<?xml version=': 0, '>': 77, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '17', 'dir': 'jupyter-structured-clean-dedup', 'id': '565009', 'license': 'MIT', 'n_tokens_mistral': 7727, 'n_tokens_neox': 7353, 'n_words': 3398, 'path': '1.functions_and_function_notation.ipynb', 'repo_name': 'Lawrence-Krukrubo/Foundational_Maths_for_AI', 'size': '23569'}