Differential operators

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Differential operators

Luigi Ballabio-3
Hi all,
        I added a few classes this morning in the Finite Differences framework,
namely, DPlus, DMinus, DZero, and DPlusDMinus. Given a discrete function u
on a grid with step h, the first three discretize the first derivative as:

D+ u[i] = (u[i+1]-u[i])/h
D- u[i] = (u[i]-u[i-1])/h
D0 u[i] = (u[i+1]-u[i-1])/2h

while the fourth discretizes the second derivative as

D+D- u[i] = (u[i+1]-2u[i]+u[i-1])/(h^2).

The release of these operators is meant to make easier for a programmer to
create its own differential operator by combining them. Also, it is a step
towards making one able to write finite differences code in Python.

For the time being, the side effect of this release is that one is now able
to calculate numerical derivatives in C++ and Python. An example in Python
(which I hope is understandable by non Python programmers also) is below.

Bye for now,
                Luigi


----------------------------------------------------------------

from QuantLib import *
from math import exp

# define a (not normalized) Gaussian with sigma = 1
def f(x):
        return exp(-x*x/2.0)

# discretize it on the range [-4,4] with step 0.01
xMin = -4.0
xMax = 4.0
h = 0.01
N = (xMax-xMin)/h + 1

# calculate the grid
x = [0]*N # creates a list of N elements
for i in range(N):
        x[i] = xMin+h*i

# calculate the values on the grid by applying f to every x
y = map(f,x)

# most of the code of this example is above and dealt with
# creating the discretized function - which quite a few times
# you already have stored somewhere.

# the actual derivation takes a few lines only:
# define the first and second derivative operators

D = DZero(N,h)
D2 = DPlusDMinus(N,h)

# and calculate the derivatives

dy = D.applyTo(y)
d2y = D2.applyTo(y)

# simple as that. You can now use your favorite plotting
# tools to check that dy and d2y indeed contain the first
# and second derivative of the defined Gaussian, respectively.