Hello
Just a short code to illustrate the type functionality. Reading input from a data file, writing the formatted results to a file and also to the console as a check. There are even more basic routes to do the same, but interesting to explore the Fortran 95 syntax further.
module schwarzschild_mod
implicit none
!integer, parameter :: dp = selected_real_kind(12,100)
integer, parameter :: dp = kind(1.0d0)
!==============================
! Derived type definition
!==============================
type :: Schwartzschild_properties
real(dp) :: S_radius
real(dp) :: S_density
end type Schwartzschild_properties
contains
!==============================
! Schwarzschild function
!==============================
function GR_Schwartzschild(mass) result(properties)
implicit none
real(dp) :: mass
type(Schwartzschild_properties) :: properties
real(dp), parameter :: G = 6.67430e-11_dp
real(dp), parameter :: c_light = 2.99792458e8_dp
real(dp), parameter :: pi = 4.0_dp * atan(1.0_dp)
properties%S_radius = 2.0_dp * G * mass / c_light**2
properties%S_density = (3.0_dp * c_light**2) / &
(8.0_dp * pi * G * properties%S_radius**2)
end function GR_Schwartzschild
end module schwarzschild_mod
program RS1
use schwarzschild_mod
implicit none
integer :: i, n, ios, ierror
character(len=25) :: Mass_object
real(dp) :: mass
type(Schwartzschild_properties) :: results
open(22, file='objects1.dat', status='old', action='read', iostat=ierror)
if (ierror /= 0) stop 'Cannot open input file'
n = 0
do
read(22, *, iostat=ios)
if (ios /= 0) exit
n = n + 1
end do
rewind(22)
open(25, file='objects1-calc.dat', status='replace')
! write header for file
write(25,'(A)') '==========================================================================='
write(25,'(A)') ' Object Mass(kg) Radius (m) Density (kg m-3)'
write(25,'(A)') '==========================================================================='
! Check results at the console
print *, ' Object Mass(kg) Radius (m) Density (kg m-3)'
print *, '==========================================================================='
do i = 1, n
read(22, *) Mass_object, mass
results = GR_Schwartzschild(mass)
write(*,'(1x,A,1x,es12.5,3x,es12.5,5x,es12.5)') &
Mass_object,mass,results%S_radius,results%S_density ! check results at console
write(25,'(1x,A,1x,es12.5,3x,es12.5,5x,es12.5)') &
Mass_object, mass, results%S_radius, results%S_density ! write results to file
end do
close(22)
close(25)
end program RS1
For anyone interested, the test data (kg), a random selection, are:
Observable_universe,8.80e+52
Milky_Way,1.60e+42
SMBH_NGC4889,4.20e+40
SMBH_Messier_87,1.30e+40
SMBH_Andromeda_Galaxy,3.40e+38
RMC_R136A1,6.2685e32
SMBH_Sagittarius_A,8.20e+36
Sun,1.99e+30
Earth,5.972e+24
Moon,7.346e+22
Jupiter,1.90e+27
Plaskett's_Star_B,1.1144e32
Donald_Trump,110
Big_Mac,0.215
Planck_mass,2.18e-8
Lester