/*
Program RK2.c wrtitten by Erik Cheever
Approximates the solution to a 1st order differential equation using a 2nd order Runge-Kutta
The problem to be solved is:
y'(t)+2*y(t)=3*exp(-4*t)
Note: this problem has a known exact solution
y(t)=2.5*exp(-2*t)-1.5*exp(-4*t)
This program is quite general, it is easily adapted to almost any problem
by changing the routine "CalcDerivs" that calculates the derivatives, and the value
of NDERIVS.
*/
#include //I/O library
#include //Math library
#define NDERIVS 1 //Number of derivatives
void CalcDerivs(int numDerivs, float *x, float t, float h, float *k1, float *k2);
void main();
void CalcDerivs(int numDerivs, float *x, float t, float h, float *k1, float *k2) {
// numDerivs is the number of derivatives to be calculated
// x is an array containing the state variables
// t is time
// h is the time step
// k1 is the array of calculated derivatives (at beginning of time step).
// k2 is the array of calculated derivatives (at end of time step).
float xapprox[NDERIVS]; //Intermediate approx of state variables.
int i; //loop counter.
k1[0]=3*exp(-4*t)-2*x[0]; //Calculate derivative at beginning of time step.
for(i=0;i