File: simple-assertions.f90

package info (click to toggle)
fortran-assert 3.1.0-5
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 212 kB
  • sloc: f90: 305; ansic: 41; makefile: 9; sh: 4
file content (30 lines) | stat: -rw-r--r-- 1,204 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
program assertion_examples
  !! Demonstrate the use of assertions as runtime checks on the satisfaction of 
  !! of two kinds of constraints:
  !! 1. Preconditions: requirements for correct execution at the start of a procedure and
  !! 2. Postconditions: requirements for correct execution at the end of a procedure.
  use assert_m, only : assert
  implicit none
  
  print *, "roots: ", roots(a=1.,b=0.,c=-4.)

contains

  pure function roots(a,b,c) result(zeros)
    !! Calculate the roots of a quadratic polynomial
    real, intent(in) :: a, b, c
    real, allocatable :: zeros(:)
    real, parameter :: tolerance = 1E-06

    associate(discriminant => b**2 - 4*a*c)
      call assert(assertion = discriminant >= 0., description = "discriminant >= 0") ! precondition
      allocate(zeros(2))
      ! there's a deliberate math bug in the following line, to help demonstrate assertion failure
      zeros = -b + [sqrt(discriminant), -sqrt(discriminant)]
    end associate

    ! This assertion will fail (due to the defect above) when ASSERTIONS are enabled:
    call assert(all(abs(a*zeros**2 + b*zeros + c) < tolerance), "All residuals within tolerance.") ! postcondition
  end function

end program