sci py
sci py
scipy can be compared to other standard scientific-computing libraries, such as the GSL (GNU Scientific Library for C and C++), or Matlab’s
toolboxes. scipy is the core package for scientific routines in Python; it is meant to operate efficiently on numpy arrays, so that numpy and
scipy work hand in hand.
scipy.interpolate Interpolation
scipy.optimize Optimization
scipy.stats Statistics
They all depend on numpy, but are mostly independent of each other. The standard way of importing Numpy and these Scipy modules is:
import numpy as np
from scipy import stats # same for other sub-modules
The main scipy namespace mostly contains functions that are really numpy functions (try scipy.cos is np.cos). Those are exposed for
historical reasons; there’s no reason to use import scipy in your code.
These constants can be helpful when you are working with Data Science.
print(constants.pi)
3.141592653589793
print(dir(constants))
['Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'ConstantWarning', 'G', 'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg', 'Stefan
print(constants.yotta) #1e+24
print(constants.zetta) #1e+21
print(constants.exa) #1e+18
print(constants.peta) #1000000000000000.0
print(constants.tera) #1000000000000.0
print(constants.giga) #1000000000.0
print(constants.mega) #1000000.0
print(constants.kilo) #1000.0
print(constants.hecto) #100.0
print(constants.deka) #10.0
print(constants.deci) #0.1
print(constants.centi) #0.01
print(constants.milli) #0.001
print(constants.micro) #1e-06
print(constants.nano) #1e-09
print(constants.pico) #1e-12
print(constants.femto) #1e-15
print(constants.atto) #1e-18
print(constants.zepto) #1e-21
1e+24
1e+21
1e+18
1000000000000000.0
1000000000000.0
1000000000.0
1000000.0
1000.0
100.0
10.0
0.1
0.01
0.001
1e-06
1e-09
1e-12
1e-15
1e-18
1e-21
print(constants.gram) #0.001
print(constants.metric_ton) #1000.0
print(constants.grain) #6.479891e-05
print(constants.lb) #0.45359236999999997
print(constants.pound) #0.45359236999999997
print(constants.oz) #0.028349523124999998
print(constants.ounce) #0.028349523124999998
print(constants.stone) #6.3502931799999995
print(constants.long_ton) #1016.0469088
print(constants.short_ton) #907.1847399999999
print(constants.troy_ounce) #0.031103476799999998
print(constants.troy_pound) #0.37324172159999996
print(constants.carat) #0.0002
print(constants.atomic_mass) #1.66053904e-27
print(constants.m_u) #1.66053904e-27
print(constants.u) #1.66053904e-27
0.001
1000.0
6.479891e-05
0.45359236999999997
0.45359236999999997
0.028349523124999998
0.028349523124999998
6.3502931799999995
1016.0469088
907.1847399999999
0.031103476799999998
0.37324172159999996
0.0002
1.6605390666e-27
1.6605390666e-27
1.6605390666e-27
print(constants.degree) #0.017453292519943295
print(constants.arcmin) #0.0002908882086657216
print(constants.arcminute) #0.0002908882086657216
print(constants.arcsec) #4.84813681109536e-06
print(constants.arcsecond) #4.84813681109536e-06
0.017453292519943295
0.0002908882086657216
0.0002908882086657216
4.84813681109536e-06
4.84813681109536e-06
print(linalg.det(arr))
-2.0
print(linalg.det(arr_2))
0.0
a=np.ones((3,4))
print(a)
print(linalg.det(a))
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-26-2d0fa98b2af7> in <cell line: 0>()
2 print(a)
3
----> 4 print(linalg.det(a))
ValueError: Last 2 dimensions of the array must be square but received shape (3, 4).
[[-2. 1. ]
[ 1.5 -0.5]]
True
---------------------------------------------------------------------------
LinAlgError Traceback (most recent call last)
<ipython-input-29-8727be865bc0> in <cell line: 0>()
1 arr = np.array([[3, 2],
2 [6, 4]]) # this brings singularity hence no inverse.
----> 3 print(linalg.inv(arr) )
# 2x+3y=8
# 5x+7y=19
import numpy as np
from scipy.linalg import solve
# Coefficients matrix
A = np.array([[2, 3], [5, 7]])
# Constants matrix
b = np.array([8, 19])
x+2y=2
3x+5y=6
6x+8y=9
(Since there are more equations than unknowns, we need to find the best approximate solution.)
# Coefficients matrix
A = np.array([[1, 2], [3, 5], [6, 8]])
# Constants vector
b = np.array([2, 6, 9])
#This gives the best possible values for x and y that minimize the error.
Computing Generalized Eigenvalues Problem: Find the generalized eigenvalues for the matrices:
`𝐴 =[4 2
3 1]`
,𝐵=[1001]
Generalized Eigenvalues:
[ 5.37228132+0.j -0.37228132+0.j]
Generalized Eigenvectors:
[[ 0.82456484 -0.41597356]
[ 0.56576746 0.90937671]]
x + cos(x)
# Example
# Find root of the equation x + cos(x):
def eqn(x):
return x + np.cos(x)
myroot = root(eqn, 0)
print(myroot.x)
[-0.73908513]
The scipy.optimize module provides algorithms for function minimization (scalar or multi-dimensional), curve fitting and root finding.
The data
import numpy as np
temp_max = np.array([17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18])
temp_min = np.array([-62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58])
plt.figure()
plt.plot(months, temp_max, 'ro')
plt.plot(days, yearly_temps(days, *res_max), 'r-')
plt.plot(months, temp_min, 'bo')
plt.plot(days, yearly_temps(days, *res_min), 'b-')
plt.xlabel('Month')
plt.ylabel('Temperature ($^\circ$C)')
plt.show()
keyboard_arrow_down Finding the minimum of a scalar function
Let’s define the following function:
def f(x):
return x**2 + 10*np.sin(x)
This function has a global minimum around -1.3 and a local minimum around 3.8.
Searching for minimum can be done with scipy.optimize.minimize(), given a starting point x0, it returns the location of the minimum that it
has found:
array([-1.30644012])
Methods: As the function is a smooth function, gradient-descent based methods are good options. The lBFGS algorithm is a good choice in
general: