|
| 1 | +program example_state2 |
| 2 | + !! This example shows how to set a `type(linalg_state)` variable to process output conditions |
| 3 | + !! out of a simple division routine. The example is meant to highlight: |
| 4 | + !! 1) the different mechanisms that can be used to initialize the `linalg_state` variable providing |
| 5 | + !! strings, scalars, or arrays, on input to it; |
| 6 | + !! 2) `pure` setup of the error control |
| 7 | + use stdlib_linalg_state |
| 8 | + implicit none |
| 9 | + integer :: info |
| 10 | + type(linalg_state_type) :: err |
| 11 | + real :: a_div_b |
| 12 | + |
| 13 | + ! OK |
| 14 | + call very_simple_division(0.0,2.0,a_div_b,err) |
| 15 | + print *, err%print() |
| 16 | + |
| 17 | + ! Division by zero |
| 18 | + call very_simple_division(1.0,0.0,a_div_b,err) |
| 19 | + print *, err%print() |
| 20 | + |
| 21 | + ! Out of bounds |
| 22 | + call very_simple_division(huge(0.0),0.001,a_div_b,err) |
| 23 | + print *, err%print() |
| 24 | + |
| 25 | + contains |
| 26 | + |
| 27 | + !> Simple division returning an integer flag (LAPACK style) |
| 28 | + elemental subroutine very_simple_division(a,b,a_div_b,err) |
| 29 | + real, intent(in) :: a,b |
| 30 | + real, intent(out) :: a_div_b |
| 31 | + type(linalg_state_type), optional, intent(out) :: err |
| 32 | + |
| 33 | + type(linalg_state_type) :: err0 |
| 34 | + real, parameter :: MAXABS = huge(0.0) |
| 35 | + character(*), parameter :: this = 'simple division' |
| 36 | + |
| 37 | + !> Check a |
| 38 | + if (b==0.0) then |
| 39 | + ! Division by zero |
| 40 | + err0 = linalg_state_type(this,LINALG_VALUE_ERROR,'Division by zero trying ',a,'/',b) |
| 41 | + elseif (.not.abs(b)<MAXABS) then |
| 42 | + ! B is out of bounds |
| 43 | + err0 = linalg_state_type(this,LINALG_VALUE_ERROR,'B is infinity in a/b: ',[a,b]) ! use an array |
| 44 | + elseif (.not.abs(a)<MAXABS) then |
| 45 | + ! A is out of bounds |
| 46 | + err0 = linalg_state_type(this,LINALG_VALUE_ERROR,'A is infinity in a/b: a=',a,' b=',b) |
| 47 | + else |
| 48 | + a_div_b = a/b |
| 49 | + if (.not.abs(a_div_b)<MAXABS) then |
| 50 | + ! Result is out of bounds |
| 51 | + err0 = linalg_state_type(this,LINALG_VALUE_ERROR,'A/B is infinity in a/b: a=',a,' b=',b) |
| 52 | + else |
| 53 | + err0%state = LINALG_SUCCESS |
| 54 | + end if |
| 55 | + end if |
| 56 | + |
| 57 | + ! Return error flag, or hard stop on failure |
| 58 | + call linalg_error_handling(err0,err) |
| 59 | + |
| 60 | + end subroutine very_simple_division |
| 61 | + |
| 62 | + |
| 63 | +end program example_state2 |
0 commit comments