Today I'm trying to evaluate this differential equation for internal energy in a gas in Fortran:
$$ \frac{du}{dt} = - \frac{n_H^2}{\rho}\frac{\Lambda}{n_H^2} $$
Where nH is the density of hydrogen in the gas (costant), u is the internal energy: $$ u(T) = \frac{1}{\gamma - 1}\frac{kT}{\mu m_p} $$
And lambda is the cooling function (depending also only on temperature), sum of all the radioactive processes in the gas that make it cool down over time.
I'm trying to solve this using a RK2 method in Fortran (Heun), and I'm sure that the actual solving algorithm works fine, but I'm not sure on how to even implement this.
I'm using this subroutine to define the right hand side of the equation:
SUBROUTINE dydx(neq, y, f)
INTEGER, INTENT(IN) :: neq
REAL*8, DIMENSION(neq), INTENT(IN) :: y
REAL*8, DIMENSION(neq), INTENT(OUT) :: f
f= -y
END SUBROUTINE dydx
Already, I'm pretty sure this is not the right way to do this. I'm trying to make it in a way such that $\frac{dy}{dx} = -f(x,y)$, but I really don't get how.
This is my Heun alg:
SUBROUTINE heun(neq, h, yold, ynew)
INTEGER, INTENT(IN) :: neq
REAL*8, INTENT(IN) :: h
REAL*8, DIMENSION(neq), INTENT(IN) ::yold
REAL*8, DIMENSION(neq), INTENT(OUT) :: ynew
REAL*8, DIMENSION(neq) :: f, ftilde
INTEGER :: i
CALL dydxv(neq, yold, f)
DO i=1, neq
ynew(i) = yold(i) + h*f(i)
END DO
CALL dydxv(neq, ynew, ftilde)
DO i=1, neq
ynew(i) = yold(i) + 0.5d0*h*(f(i) + ftilde(i))
END DO
END SUBROUTINE heun
And I think this one's fine. This is how I'm calling it (lambda, E_0-the constants-, density are arrays of size n where I stored all the values given by their respective functions in the temperatures I'm considering):
DO i = 1,n
CALL heun(n, h, -lambda/(E_0*density), temperature)
ENDDO
I want to plot the results against a timescale in units of cooling time, which I can calculate analytically as: $$ t_{cool} = \frac{u}{(\frac{\Lambda}{\rho})} $$
And this is the graph I get using this implementation:
Which looks off but at least it's going down, since it's supposed to be cooling down.
My final goal is to have a starting temperature of a million Kelvin and simulate cooling until ten thousand Kelvin, and see how long the process takes (compared to the analytical cooling time). How do I implement this boundary conditions?
I know I'm asking many questions but I hardly know where to start when it comes to numerical differentiation. If you could at least give me a starting point or good resources on where to get started, it would be very much appreciated.