import os, sys, glob
from pathlib import Path
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = 'all'
from sympy import *
var('x, y, z, a, b, c, α, β, γ, σ')
init_printing()
1 + 1
1 * 2
3 ** 2
3 / 2
3 // 2 # integer division
9 % 5 # modulo
type(3)
type(3.5)
int(3.8)
from fractions import Fraction
f = Fraction(2, 3)
f + 1
a = 2 + 3j
a
a = float(input())
a + 1
try:
a = float(input('Enter a number: '))
except ValueError:
print('You entered an invalid number')
def multi_table(a):
for i in range(1, 11):
print(f'{a} x {i} = {a*i}')
multi_table(5)
solve for x $a x^2 + b x + c = 0$
$$ x = \frac{- b \pm \sqrt{b^2 - 4ac}}{2a} $$def quad_solver(a, b, c):
D = (b**2 - 4*a*c)**.5
return([ (-b + D) / (2*a), (-b - D) / (2*a) ])
quad_solver(4,5,-2)
from pylab import plot, show
x = range(1, 11)
y = [x**2 for x in x]
plot(x, y, marker = 'o')
plot(x, y, 'o')
# 2. Define data
x = np.arange(0, 4 * np.pi, 0.2)
y = np.sin(x)
# 3. Plot data including options
plt.plot(x, y,
linewidth=0.5,
linestyle='--',
color='r',
marker='o',
markersize=10,
markerfacecolor=(1, 0, 0, 0.1))
# 4. Add plot details
plt.title('Plot of sin(x) vs x from 0 to 4 pi')
plt.xlabel('x (0 to 4 pi)')
plt.ylabel('sin(x)')
plt.legend(['sin(x)']) # list containing one string
plt.xticks(
np.arange(0, 4*np.pi + np.pi/2, np.pi/2),
['0','pi/2','pi','3pi/2','2pi','5pi/2','3pi','7pi/2','4pi'])
plt.grid(True)
# 5. Show the plot
plt.show()
plt.savefig('plot.png', dpi=300, bbox_inches='tight')
x = np.arange(0,4*np.pi,0.1)
y = np.sin(x)
z = np.cos(x)
f, ax = plt.subplots()
ax.plot(x,y)
ax.plot(x,z)
ax.set_title('Two Trig Functions')
ax.legend(['sin','cos'])
ax.xaxis.set_label_text('Angle θ')
ax.yaxis.set_label_text('Sine and Cosine')
# random but semi-focused data
x1 = 1.5 * np.random.randn(150) + 10
y1 = 1.5 * np.random.randn(150) + 10
x2 = 1.5 * np.random.randn(150) + 4
y2 = 1.5 * np.random.randn(150) + 4
x = np.append(x1,x2)
y = np.append(y1,y2)
colors = np.random.rand(150*2)
area = np.pi * (8 * np.random.rand(150*2))**2
fig, ax = plt.subplots(1, 2, figsize = (10, 8))
ax[0].scatter(x,y)
ax[1].scatter(x, y, s=area, c=colors, alpha=0.6)
ax[1].set_title('Scatter plot of x-y pairs semi-focused in two regions')
ax[1].set_xlabel('x value')
ax[1].set_ylabel('y value')
# generate some random data
data1 = np.random.normal(0, 6, 100)
data2 = np.random.normal(0, 7, 100)
data3 = np.random.normal(0, 8, 100)
data4 = np.random.normal(0, 9, 100)
data = list([data1, data2, data3, data4])
fig, ax = plt.subplots(1, 2, figsize = (10, 8))
# build a box plot
ax[0].boxplot(data)
# title and axis labels
ax[0].set_title('box plot')
ax[0].set_xlabel('x-axis')
ax[0].set_ylabel('y-axis')
xticklabels=['category 1', 'category 2', 'category 3', 'category 4']
ax[0].set_xticklabels(xticklabels)
# add horizontal grid lines
ax[0].yaxis.grid(True)
# build a violin plot
ax[1].violinplot(data, showmeans=False, showmedians=True)
# add title and axis labels
ax[1].set_title('violin plot')
ax[1].set_xlabel('x-axis')
ax[1].set_ylabel('y-axis')
# add x-tick labels
xticklabels = ['category 1', 'category 2', 'category 3', 'category 4']
ax[1].set_xticks([1,2,3,4])
ax[1].set_xticklabels(xticklabels)
# add horizontal grid lines
ax[1].yaxis.grid(True)
mu = 80
sigma = 7
x = np.random.normal(mu, sigma, size=200)
fig, ax = plt.subplots()
ax.hist(x, 20)
ax.set_title('Historgram')
ax.set_xlabel('bin range')
ax.set_ylabel('frequency')
fig.tight_layout()
# Data
aluminum = np.array([
6.4e-5, 3.01e-5, 2.36e-5, 3.0e-5, 7.0e-5, 4.5e-5, 3.8e-5, 4.2e-5, 2.62e-5,
3.6e-5
])
copper = np.array([
4.5e-5, 1.97e-5, 1.6e-5, 1.97e-5, 4.0e-5, 2.4e-5, 1.9e-5, 2.41e-5, 1.85e-5,
3.3e-5
])
steel = np.array([
3.3e-5, 1.2e-5, 0.9e-5, 1.2e-5, 1.3e-5, 1.6e-5, 1.4e-5, 1.58e-5, 1.32e-5,
2.1e-5
])
# Create arrays for the plot
materials = ['Aluminum', 'Copper', 'Steel']
x_pos = np.arange(len(materials))
aluminum_mean = np.mean(aluminum)
copper_mean = np.mean(copper)
steel_mean = np.mean(steel)
# Calculate the standard deviation
aluminum_std = np.std(aluminum)
copper_std = np.std(copper)
steel_std = np.std(steel)
CTEs = [aluminum_mean, copper_mean, steel_mean]
error = [aluminum_std, copper_std, steel_std]
# Build the plot
fig, ax = plt.subplots()
ax.bar(x_pos, CTEs,
yerr=error,
align='center',
alpha=0.5,
ecolor='black',
capsize=10)
ax.set_ylabel('Coefficient of Thermal Expansion')
ax.set_xticks(x_pos)
ax.set_xticklabels(materials)
ax.set_title('Coefficent of Thermal Expansion (CTE) of Three Metals')
ax.yaxis.grid(True)
# Save the figure and show
plt.tight_layout()
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = ['Civil', 'Electrical', 'Mechanical', 'Chemical']
sizes = [15, 50, 45, 10]
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, autopct='%1.1f%%')
ax.axis('equal') # Equal aspect ratio ensures the pie chart is circular.
ax.set_title('Engineering Diciplines')
from mpl_toolkits.mplot3d import axes3d
x = np.arange(-5,5,0.1)
y = np.arange(-5,5,0.1)
X,Y = np.meshgrid(x,y)
Z = X*np.exp(-X**2 - Y**2)
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111, projection='3d')
# Plot a 3D surface
ax.plot_surface(X, Y, Z)
man_mean = lambda x: sum(x)/len(x)
def man_median(num):
num.sort()
l = len(num)
if l % 2 == 0:
med = num[int(l/2)]
else:
med = num[int(l/2 + 1)]
return med
sc = [100, 60, 70, 900, 100, 200, 500, 500, 503, 600, 1000, 1200]
man_mean(sc)
np.mean(sc)
man_median(sc)
np.median(sc)
from collections import Counter
def man_mode(num):
c = Counter(num)
return c.most_common(1)[0][0]
scores = [7, 8, 9, 2, 10, 9, 9, 9, 9, 4, 5, 6, 1, 5, 6, 7, 8, 6, 1, 10]
man_mode(scores)
def freq_table(num):
c = Counter(num)
ftable = '\n'.join([f'{n[0]}\t{n[1]}' for n in c.most_common()])
return ftable
print(freq_table(scores))
man_range = lambda num: max(num) - min(num)
man_range(scores)
from sympy import *
init_printing()
var('x, y, z, α, β, γ, φ, ω, ε')
a, b, c, k, m, n = symbols('a b c k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)
Expressions
Rational(3, 2)*pi + exp(I * x) / (x**2 + y)
Evaluate at value
exp(I*x).subs(x,pi).evalf()
expr = (x + y) ** 2
expr.expand()
exp = x**2 + 5*x + 3
exp
e = x**2 - y**2
e.factor()
e.subs({x : 4, y : 1 - x})
limit(1/x,x,0,dir="-")
limit(1/x**2,x,0,dir='+')
exp = x**2 + 5*x + 3
exp
solve(exp, x)
exp = Eq(x**2 + 5*x + 3, 0)
exp
solve(exp)
solve(a * x **2 + b * x + c, x)
solveset(a * x **2 + b * x + c, x)
solveset(x ** 2 + 1, x, domain=S.Reals)
solve([x + 5*y - 2, -3*x + 6*y - 15], [x, y], dict = True)
eq1 = Eq(x + y - 5, 0)
eq2 = Eq(x - y + 3, 0)
solve((eq1, eq2), (x, y))
ineq = (10000 / x) - 1 < 0
solveset(ineq, x, S.Reals)
from sympy.solvers.inequalities import *
reduce_inequalities([x + 4*y - 2 > 0,
x - 3 + 2*y <= 5],
[x])
from sympy.polys import Poly
solve_poly_inequalities(((
Poly(x**2 - 3), "<"), (
Poly(-x**2 + 1), ">")))
Verify graphically
p = plot(x**2 - 3, -x**2 + 1, show = False)
p[0].line_color = 'r'
p[1].line_color = 'b'
p.show()
a, b = symbols('a b')
s = Sum(6*n**2 + 2**n, (n, a, b))
s
s.doit()
p = product(n*(n+1), (n, 1, b))
p
p.doit()
limit((sin(x)-x)/x**3, x, 0)
diff(cos(x**2)**2 / (1+x), x)
integrate(x**2 * cos(x), x)
integrate(x**2 * cos(x), (x, 0, pi/2))
dsolve(Eq(Derivative(f(x),x,x) + 9*f(x), 1), f(x))
from sympy.plotting import plot
p = plot(x ** 2 - 5, 5*x + 2, legend = True, show = False)
p[0].line_color = 'b'
p[1].line_color = 'r'
p.show()
p = plot( (x, (x,-5,5)), (x**2, (x,-2,2)), (x**3, (x,-3,3)),
xlabel='x',
ylabel='f(x)', legend = True, show = False)
p[0].line_color = 'b'
p[1].line_color = 'g'
p[2].line_color = 'r'
p.show()
s = FiniteSet(2, 4, 6)
s
{'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
4 in s
np.array([1,2,3])
arange(start, stop, step)
np.arange(0, 10+2, 2)
np.linspace(start, stop, number of elements)
np.linspace(0,2*np.pi,10)
np.logspace(start, stop, number of elements, base=<num>)
np.logspace(1, 2, 5 )
my_array = np.zeros((rows,cols))
np.zeros((5,5))
my_array = np.ones((rows,cols))
np.ones((3,5))
np.eye(dim)
np.eye(5)
Meshgrid / np.mgrid[]
X, Y = np.mgrid[0:5,0:11:2]
print(X)
print(Y)
Random Integers
np.random.randint(lower limit, upper limit, number of values)
np.random.randint(0,10,5)
Random numbers on unit interval np.random.rand(number of values)
np.random.rand(5)
Random choice np.random.choice(list of choices, number of choices)
lst = [1,5,9,11]
np.random.choice(lst,3)
Draw from Standard Normal distribution np.random.randn(number of values)
np.random.randn(10)
μ = 70
σ = 6.6
sample = [σ * np.random.randn(1000) + μ]
plt.hist(sample)
a = np.array([[2,3,4],[6,7,8]])
a
a[1,2]
a = np.array([2, 4, 6])
a
a[:2]
a = np.array([[2, 4, 6, 8], [10, 20, 30, 40]])
a
a[0:2, 0:3]
a[:2, :] #[first two rows, all columns]
a = np.array([1, 2, 3])
a + 2
a * 3
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
a * b
np.dot(a, b)
np.cross(a, b)
a = np.array([1, 2, 3])
np.exp(a)
np.log(a)
np.log(np.e)
np.log10(1000)
Trig
a = np.array([0, np.pi/4, np.pi/3, np.pi/2])
print(np.sin(a))
print(np.cos(a))
print(np.tan(a))
A = np.array([[8, 3, -2], [-4, 7, 5], [3, 4, -12]])
A
b = np.array([9, 15, 35])
b
np.linalg.solve(A, b)