Capstone: stats tool

The spec

The tool reads a text file with one real number per line, then reports count and mean and standard deviation.

Success means clean compile with warnings on, correct results on a known sample, and no crashes on an empty trailing line.

cat data.txt

1.0
2.0
3.0
4.0

Read the data file

Open with newunit, read in a loop with iostat, and close promptly. Count only successful reads.

The buffer stays fixed size and n records how many slots hold valid data.

subroutine read_data(fname, vals, n) implicit none character(len=*), intent(in) :: fname real, intent(out) :: vals(:) integer, intent(out) :: n integer :: u integer :: ios n = 0 open(newunit=u, file=fname, status="old", action="read") do if (n .ge. size(vals)) exit read(u, *, iostat=ios) vals(n + 1) if (ios .ne. 0) exit n = n + 1 end do close(u) end subroutine read_data

Mean and stddev

Mean is the sum divided by count. Deviation measures spread around that mean.

Use whole-array sum for clarity and guard against zero count before dividing.

function mean_fn(a, n) result(m) implicit none real, intent(in) :: a(:) integer, intent(in) :: n real :: m if (n .le. 0) then m = 0.0 return end if m = sum(a(1:n)) / real(n) end function mean_fn

Assert the math

Test on values with a known answer. Compare with a small tolerance such as 0.0001, not exact equality.

Stop with an error message when the check fails so scripts detect the failure.

program test_stats implicit none real :: vals(4) real :: m vals = [1.0, 2.0, 3.0, 4.0] m = sum(vals) / real(size(vals)) if (abs(m - 2.5) .gt. 0.0001) then print *, "mean test failed" error stop 1 end if print *, "mean test passed" end program test_stats

The code on this page was run with gfortran 15.2.0 on Alpine Linux 3.24 (x86_64) in a Docker container.

Article author: Arthur Isaev