ode_harmonic_rk2

# ode_harmonic_rk2 - { yin[0] = y[i]; yin[1] = z[i];...

This preview shows pages 1–2. Sign up to view the full content.

/* ode_harmonic_rk2.c * Example code to solve d^2y/dx^2=-y using second order Runge-Kutta. */ #include <stdio.h> #define N 2 /* number of ODEs */ #define NSTEP 100 /* number of integration steps */ #define XMIN 0.0 /* starting point for integration */ #define XMAX 4.0*3.14159265 /* stopping point for integration */ #define Y0 0.0 /* initial value */ #define Z0 1.0 /* initial value */ void derivs(float xin, float yin[], float dydx[]); void rk2(float xin, float yin[], float yout[], float h); int main() { int i=0; float h = (XMAX - XMIN)/NSTEP; /* stepsize for integration */ float yin[N], yout[N]; float x[NSTEP+1], y[NSTEP+1], z[NSTEP+1]; for (i = 0; i <= NSTEP; i++) /* Define array of x values */ x[i] = XMIN + h*i; y[0]=Y0; /* initial value */ z[0]=Z0; /* initial value */ printf("%f %f %f\n", x[0], y[0], z[0]); for (i = 0; i < NSTEP; i++) /* do integration */

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: { yin[0] = y[i]; yin[1] = z[i]; rk2(x[i], yin, yout, h); /* do one integration step */ y[i+1] = yout[0]; z[i+1] = yout[1]; printf("%f %f %f\n", x[i+1], y[i+1], z[i+1]); } return 0; } void derivs(float xin, float yin, float dydx) { /* evaluate RHSs of ODEs */ dydx[0] = yin[1]; dydx[1] = -yin[0]; return; } void rk2(float xin, float yin, float yout, float h) { /* Second order Runge-Kutta scheme */ int i; float k1[N], k2[N], yt[N], dydx[N]; /* N is the number of ODEs */ /* Evaluate k1 */ derivs(xin, yin, dydx); for (i = 0; i < N; i++) { k1[i] = h*dydx[i]; yt[i] = yin[i] + 0.5*k1[i]; } /* Evaluate k2, then update the dependent variable */ derivs(xin + 0.5*h, yt, dydx); for (i = 0; i < N; i++) { k2[i] = h*dydx[i]; yout[i] = yin[i] + k2[i]; } return; }...
View Full Document

## This note was uploaded on 09/29/2009 for the course COSC 1002 taught by Professor Wheatland during the Three '09 term at University of Sydney.

### Page1 / 2

ode_harmonic_rk2 - { yin[0] = y[i]; yin[1] = z[i];...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online