! From: "COMPUTATIONAL PHYSICS, 2nd Ed" ! by RH Landau, MJ Paez, and CC Bordeianu ! Copyright Wiley - VCH, 2007. ! Electronic Materials copyright: R Landau, Oregon State Univ, 2007; ! MJ Paez, Univ Antioquia, 2007; and CC Bordeianu, Univ Bucharest, 2007. ! Supported by the US National Science Foundation ! ! rk4.f90: 4th order rk solution for harmonic oscillator Program oscillator Implicit none ! n: number of equations, min/max in x, dist: length of x - steps ! y(1): initial position, y(2):initial velocity Real*8 :: dist, min1, max1, x, y(5) Integer :: n n = 2 min1 = 0.0; max1 = 10.0 dist = 0.1 y(1) = 1.0; y(2) = 0. open(6, File = 'rk4.dat', Status = 'Unknown') ! Do n steps rk algorithm Do x = min1, max1, dist call rk4(x, dist, y, n) write (6, *) x, y(1) End Do close(6) Stop 'data saved in rk4.dat' End Program oscillator ! End of main Program subroutine rk4(x, xstep, y, n) ! rk4 subroutine Implicit none Real*8 :: deriv, h, x, xstep, y(5) Real*8, dimension(5) :: k1, k2, k3, k4, t1, t2, t3 Integer :: i, n h = xstep/2.0 Do i = 1, n k1(i) = xstep * deriv(x, y, i) t1(i) = y(i) + 0.5*k1(i) End Do Do i = 1, n k2(i) = xstep * deriv(x + h, t1, i) t2(i) = y(i) + 0.5*k2(i) End Do Do i = 1, n k3(i) = xstep * deriv(x + h, t2, i) t3(i) = y(i) + k3(i) End Do Do i = 1, n k4(i) = xstep * deriv(x + xstep, t3, i) y(i) = y(i) + (k1(i) + (2.*(k2(i) + k3(i))) + k4(i))/6.0 End Do Return End ! Function Returns derivatives Function deriv(x, temp, i) Implicit none Real*8 :: deriv, x, temp(2) Integer :: i If (i == 1) deriv = temp(2) If (i == 2) deriv = - temp(1) Return End