The code below works however I'm having trouble storing the final result as I'd like to. I solve for the variable x which depends on t, so I want to store x(t) as a 1D array. For each value of t, I have a different value of x.
I am having trouble doing so since I do not know how many iterations the DO WHILE loop will necessarily take, so I do not know how to write the data to a variable-size array file. As of now, I just write the results for x and t to the screen.
How can I store the solution x(t) in a single 1D array? I want to have an array such that, given an input value of time t, it gives me the value of x at this time.
program RK4
implicit none
real :: a,b,x,dt,t,f,xn,k1,k2,k3,k4,phi
integer :: n=100.
write(*,*) 'enter an initial time, final time, x(0) = '
read(*,*) a,b,x
t = a !start time here... initial time
dt = (b-a)/real(n)
do while (t < b)
k1 = f(x,t)
k2 = f(x+k1*dt/2., t+dt/2.)
k3 = f(x+k2*dt/2., t+dt/2.)
k4 = f(x+k3*dt, t+dt)
phi = (1./6.)*(k1+2.*k2+2.*k3+k4)
xn = x + dt*phi
t = t + dt
x = xn
write(*,*) 'the results for position and time are given by', x,t !This prints out the results, but I want to store this in a single variable as x(t).
end do
end program RK4
function f(x,t)
real, intent(in) :: x,t
f = -2*x
end function f