I have a function that solves equations of a certain form without needing to know all about it in an attempt to keep it generic. This can be achieved by requiring all equations that need solving to specify args even if they don't use it, but I think this is a bit hacky. Is there a better way to handle this?
- Code: Select all
def dif_eq1(x, y, args):
''' We need to specify args even if we don't use it '''
return - 2 * y + x + 4
def dif_eq2(x, y, args):
a, b = args
return - 2 * y + x * a + 4 / b
def RK4(dydx, dx, x, y, args):
''' Arguments: (function to solve,
initial x value,
initial y value,
arguments required by function to solve)
This function should not have to know what args is '''
x = [x]
y = [y]
steps = 100
h = dx / steps
for n in xrange(steps):
k1 = h * dydx(x[n], y[n], args)
k2 = h * dydx(x[n] + h/2, y[n] + k1/2, args)
k3 = h * dydx(x[n] + h/2, y[n] + k2/2, args)
k4 = h * dydx(x[n] + h, y[n] + k3, args)
k = (k1 + 2 * k2 + 2 * k3 + k4) / 6
x.append(x[n] + h)
y.append(y[n] + k)
return x, y
''' Here we do need to know what args is '''
x1, y1 = RK4(dif_eq1, 2., 0, 1, None)
x2, y2 = RK4(dif_eq2, 2.5, 0, 1, (2, 3))