16 KiB
16 KiB
In [ ]:
from scipy.interpolate import interp1dIn [ ]:
import numpy as np
x = np.array([0., 1., 3., 4.])
y = np.array([0., 4., 2.7, 2.08])In [ ]:
f = interp1d(x,y)In [ ]:
type(f)In [ ]:
f(0.5)In [ ]:
f(3.3)In [ ]:
f(np.array([0.5, 1.5, 2.5, 3.5]))In [ ]:
f(-1.)In [ ]:
f = interp1d(x, y, bounds_error=False, fill_value=-10.)In [ ]:
f(-1.0)In [ ]:
f(np.array([-1., 1., 3., 6.]))In [ ]:
f = interp1d(x, y, kind='cubic')
f(0.5)In [ ]:
import matplotlib.pyplot as plt
%matplotlib inlineIn [ ]:
xp=np.arange(0,4,0.1)
f = interp1d(x,y)
g = interp1d(x,y,kind=2) # equivalent to 'quadratic'
h = interp1d(x,y,kind=3) # equivalen to 'cubic'
plt.plot(xp,f(xp),xp,g(xp),xp,h(xp))
plt.xlim(0,6)
plt.legend(['linear','quadratic spline','cubic spline'])In [ ]:
def orig(x):
return 3.11-3.11*(x-1)*(x-1)+0.5*x+0.39*x*x*x
xp=np.arange(0,4,0.5)
print (xp)
print (orig(xp))
print (h(xp))In [ ]:
def simple_function(x):
return 3. * x**2 + 2. * x + 1.In [ ]:
from scipy.integrate import quad
print(quad(simple_function, 1., 2.))In [ ]:
x = np.linspace(1., 2., 1000)
y = 3. * x**2 + 2. * x + 1.In [ ]:
from scipy.integrate import simpson
print(simpson(y, x=x))In [ ]:
from scipy.integrate import trapz
print(trapz(y, x=x))In [ ]:
# your solution ..In [ ]:
# your solution here
# Note the following EXAMPLE
# for the 'args' argument (tuple) to be passed to the function to be integrated
#
# if only one argument is passed, it should be done like this: (1,) so that it still is a tuple
def func(x,a,b):
return result
quad(func,0,1,args=(1,1))
In [ ]:
# your solution hereIn [ ]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from scipy.integrate import odeintIn [ ]:
def diffeq(x, t,k,g):
#define/clear derivative
dxdt = np.zeros(2)
""" differential equation for damped oscillation
split into first-order equation
x. = v
v. = - k x - 2 gamma v
"""
dxdt[0] = x[1]
dxdt[1] = -k * x[0] - 2 * g * x[1]
return dxdt
""" constants """
k=0.1
g=0.1
x = np.array([2.0,-0.8]) # initial position
time = np.linspace(0.0,100.0,100) # evaluation times
""" calling the solver """
solution = odeint(diffeq, x, time, args=(k,g))In [ ]:
def damped_oscillation(t,x,k,g):
om=np.sqrt(k-g**2)
A=(x[1]+g*x[0])/om
B=x[0]
return (A*np.sin(om*t)+B*np.cos(om*t))*np.exp(-g*t)In [ ]:
plt.plot(time,solution[:,0],time,damped_oscillation(time,x,k,g))
plt.legend(['Numerical','Analytical'])In [ ]:
# solution hereIn [ ]:
# solution hereIn [ ]:
# solution here