Function plots

This notebook just contains some common functions for discussion in class.

Libraries

In [1]:
# numpy is for efficient numerical methods.
import numpy as np
# pyplot is for plotting.
import matplotlib.pyplot as pl
In [2]:
# Set x to an array of 1000 evenly spaced values between -10 and 10.
x = np.linspace(-10.0, 10.0, 1000)

Linear

Linear relationships in one variable are of the form $y = mx + c$.

In [3]:
# Lines with the same c value hit the y-axis at the same spot.
pl.plot(x,  5.0 * x + 7.0, 'b', label=r'$5x + 7$')
pl.plot(x, 10.0 * x + 7.0, 'g', label=r'$10x + 7$')
pl.plot(x, -5.0 * x + 7.0, 'r', label=r'$-5x + 7$')

pl.legend()
pl.show()
In [4]:
# Distinct lines with the same slope are paralell.
pl.plot(x,  5.0 * x +  7.0, 'b', label=r'$5x +  7$')
pl.plot(x,  5.0 * x + 14.0, 'g', label=r'$5x + 14$')
pl.plot(x,  5.0 * x + 21.0, 'r', label=r'$5x + 21$')

pl.legend()
pl.show()

Powers

In [5]:
# y is the square of x.
y = x**2

pl.plot(x, y, label=r'$x^2$')
pl.legend()
pl.show()
In [6]:
# y is the cube of x.
y = x**3

pl.plot(x, y, label=r'$x^3$')
pl.legend()
pl.show()
In [7]:
# Fourth power.
y = x**4

pl.plot(x, y, label=r'$x^4$')
pl.legend()
pl.show()
In [8]:
# Fifth.
y = x**5

pl.plot(x, y, label=r'$x^5$')
pl.legend()
pl.show()
In [9]:
# Sixth.
y = x**6

pl.plot(x, y, label=r'$x^6$')
pl.legend()
pl.show()
In [10]:
# Seventh.
y = x**7

pl.plot(x, y, label=r'$x^7$')
pl.legend()
pl.show()

Exponential

In [11]:
# e to the x.
y = np.exp(x)

pl.plot(x, y, label=r'$e^x$')
pl.legend()
pl.show()

Square root

In [12]:
# This will only work for positive x, unless we allowed i.
y = np.sqrt(x[x >= 0])

pl.plot(x[x >= 0], y, label=r'$\sqrt{x}$')
pl.legend()
pl.show()

Shifts

In [13]:
# Plot x^2 + 100 and x^2 - 100 on the same axes.

y = x**2 + 100
pl.plot(x, y, label=r'$x^2 + 100$')

y = x**2 - 100
pl.plot(x, y, label=r'$x^2 - 100$')

pl.legend()
pl.show()

Moving roots

In [14]:
# x^2 - 4x + 4 = (x - 2)^2
y = x**2 - 4*x + 4
pl.plot(x, y, label=r'$x^2 - 4x + 4$')
pl.legend()
pl.show()

Hyperbolic functions

In [15]:
# tanh(x) = sinh(x)/cosh(x) = (e^x - e^-x) / (e^x + e^-x)
y = np.tanh(x)

pl.plot(x, y, label=r'$\tanh(x)$')
pl.legend()
pl.show()

Sigmoid function

In [16]:
# 1 / (1 + e^-x)
y = 1 / (1 + np.exp(-x))

pl.plot(x, y, label=r'$S(x)$')
pl.legend()
pl.show()

End