Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Question 3:

Develop a program to find the inverse of DFT... of x.

Solution:

import numpy as np

def dft_inverse(X):
N = len(X)
n = np.arange(N)
k = n.reshape((N, 1))
e = np.exp(-2j * np.pi * k * n / N)

np.dot(e, X)

x = np.dot(e, X)/N

return x
Question 4:
Write a funcion my_cubic_spline (x, y, X) where x and y
arrays that contain experimental data points,and X is an array
Asume that x and X are ascendong order and have unique element
The output argument Y should be ал array the same size as X, , where
Y[i] is cubic spline interpolation of X[i]. Do not use interp1d or CubSpline.

Solution:

import numpy as np

def my_cubic_spline(x, y, X):


n = len(x)
a = y.copy()
b = np.zeros(n)
d = np.zeros(n)

# Calculate coefficients of natural cubic spline


h = x[1:] - x[:-1]
alpha = (3 * (a[1:] - a[:-1])) / h
c = np.zeros(n+1)
l = np.ones(n+1)
mu = np.zeros(n+1)
z = np.zeros(n+1)

for i in range(1, n):


l[i] = 2 * (x[i+1] - x[i-1]) - h[i-1] * mu[i-1]
mu[i] = h[i] / l[i]
z[i] = (alpha[i-1] - h[i-1]*z[i-1]) / l[i]

for j in range(n-1, 0, -1):


c[j] = z[j] - mu[j] * c[j+1]
b[j] = (a[j+1] - a[j]) / h[j] - h[j] * (c[j+1] + 2 * c[j]) / 3
d[j] = (c[j+1] - c[j]) / (3 * h[j])

# Evaluate cubic spline at X


Y = np.zeros_like(X)
for i in range(len(X)):
j = np.searchsorted(x, X[i])
if j == 0:
j=1
elif j == n:
j=n-1

dx = X[i] - x[j]
Y[i] = a[j] + b[j] * dx + c[j] * dx**2 + d[j] * dx**3

return Y

You might also like