Import Modules


In [9]:
import numpy as np                #handles arrays of values similar to MATLAB
from scipy import linalg          #contains certain operators you may need for class
import matplotlib.pyplot as plt   #contains everything you need to create plots
import sympy as sy
from sympy.functions import ln
import math

Performing basic math functions


In [10]:
x = 2
print('2*x =',2*x)        #multiplcation
print('x^3 =',x**3)       #exponents
print('e^x =',np.exp(x))  #e^x
print('e^x =',np.e**x)    #e^x alternate form
print('Pi =',np.pi)       #Pi


2*x = 4
x^3 = 8
e^x = 7.38905609893
e^x = 7.3890560989306495
Pi = 3.141592653589793

Integration

This will integrate a function that you provide. There a number of other methods for numerical integration that can be found online.

For our examples we will use:

$I = \int_{0}^{1} ax^2 + b dx$


In [11]:
from scipy.integrate import quad

In [12]:
# First define a function that you want to integrate
def integrand(x,a,b):
    return a*x**2 + b

# Set your constants 
a = 2
b = 1
I = quad(integrand, 0, 1, args=(a,b))
print(I)
# I has two values, the first value is the estimation of the integration, the second value is the upper bound on the error.
# Notice that the upper bound on the error is extremely small, this is a good estimation.


(1.6666666666666667, 1.8503717077085944e-14)

Arrays


In [13]:
y = np.array([1,2,3,4,5])             #create an array of values
print('y =\t',y)                      #'\t' creates an indent to nicely align answers 
print('y[0] =\t',y[0])                           #Python starts counting at 0
print('y[2] =\t',y[2])                           #y[2] gives the third element in y (I don't agree with this syntax but what can ya do?)
print('y*x =\t',y*x)

x = np.array([6,7,8,9])
z = np.concatenate((y,x),axis=None)   #concatenate two arrays
print('[y,x] =\t',z)
print('sum of y elements =\t',np.sum(y))                      #sum the elements of an array
print('sum of z elements =\t',np.sum(z))


y =	 [1 2 3 4 5]
y[0] =	 1
y[2] =	 3
y*x =	 [ 2  4  6  8 10]
[y,x] =	 [1 2 3 4 5 6 7 8 9]
sum of y elements =	 15
sum of z elements =	 45

for loops


In [14]:
#This first loop iterates over the elements in an array
array = np.array([0,1,2,3,4])
print('Frist Loop')
for x in array:
    print(x*2)

#This second loop iterates for x in the range of [0,4], again we have to say '5' because of the way Python counts
print('Second Loop')
for x in range(5):
    print(x*2)


Frist Loop
0
2
4
6
8
Second Loop
0
2
4
6
8

Summation with for loops

$\sum_{n=1}^{4} 2^{-n}$


In [15]:
answer = 0                      #Each iteration will be added to this, so we start it at zero
storage = []                    #This will be used to store values after each iteration
for n in range(1,5):
    storage.append(2**(-n))     #The append command adds elements to an array
    answer+=2**(-n)             #+= is the same as saying answer = answer + ...
print('answer =\t',answer)
print('stored values=\t',storage)


answer =	 0.9375
stored values=	 [0.5, 0.25, 0.125, 0.0625]

while loops


In [16]:
#This while loop accomplishes the same thing as the two for loops above
x=0
while x<5:
    print(x*2)
    x+=1


0
2
4
6
8

if statements


In [17]:
#Order of your if statements matters. 
array = np.array([2,4,6,7,11])
for x in array:
    if x<5:
        print('Not a winner')
    elif x<10:
        print(2*x)
    else:
        break


Not a winner
Not a winner
12
14

Linear Algebra


In [18]:
#Create a matrix
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print('a =\n',a)

#get eigenvalues and eigvenvectors of a
w,v = linalg.eig(a) 
print('eigenvalues =\t',w)
print('eigenvectors =\n',v)

#Matrix multiplication
b = np.array([1,0,0])
print('a*b =\t',a@b.T)     #'@' does matrix multiplication, '.T' transposes a matrix or vector


a =
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
eigenvalues =	 [  1.61168440e+01+0.j  -1.11684397e+00+0.j  -1.30367773e-15+0.j]
eigenvectors =
 [[-0.23197069 -0.78583024  0.40824829]
 [-0.52532209 -0.08675134 -0.81649658]
 [-0.8186735   0.61232756  0.40824829]]
a*b =	 [1 4 7]

Creating a function


In [19]:
#'def' starts the function. Variables inside the parentheses are inputs to your function. 
#Return is what your function will output.
#In this example I have created a function that provides the first input raised to the power of the second input. 

def x2y(x,y):
    return x**y

x2y(4,2)


Out[19]:
16

Symbolic Math


In [20]:
#This lets us create functions with variables
#First define a variable
x = sy.Symbol('x')

#Next create a function
function = x**4

der = function.diff(x,1)
print('first derivative =\t',der)

der2 = function.diff(x,2)
print('second derivative =\t',der2)

#You can substitute back in for symbols now
print('1st derivative at x=2 =\t',der.subs(x,2))
print('2nd derivative at x=2 =\t',der2.subs(x,2))

function2 = ln(x)

lnder = function2.diff(x,1)
print('derivative of ln(x) =\t',lnder)


first derivative =	 4*x**3
second derivative =	 12*x**2
1st derivative at x=2 =	 32
2nd derivative at x=2 =	 48
derivative of ln(x) =	 1/x

Plotting


In [21]:
#Standard plot

x = np.linspace(0,10)
y = np.sin(x)
z = np.cos(x)

plt.plot(x,y,x,z)
plt.xlabel('Radians');
plt.ylabel('Value');
plt.title('Standard Plot')
plt.legend(['Sin','Cos'])
plt.show()

#Scatter Plot

x = np.linspace(0,10,11)
y = np.sin(x)
z = np.cos(x)

plt.scatter(x,y)
plt.scatter(x,z)
plt.xlabel('Radians');
plt.ylabel('Value');
plt.title('Scatter Plot')
plt.legend(['Sin','Cos'])
plt.show()


Math package has useful tools as well


In [22]:
print('5! =\t',math.factorial(5))
print('|-3| =\t',math.fabs(-3))


5! =	 120
|-3| =	 3.0

Putting it to use

Use 'for' loops to create Taylor expansions of $ln(1+x)$ centered at 0, with an order of 1, 2, 3, and 4. Plot these Taylor expansions along with the original equation on one plot. Label your plots.

As a reminder the formula for a Taylor expansion is:

$f(a) + \sum_{n=1}^{\infty}\frac{f^n(a)}{n!}(x-a)^n$

Since our expansion is centered at zero, $a=0$.


In [23]:
#Insert code here.

Additional Resources


In [ ]: