Jump to content

Averages/Arithmetic mean: Difference between revisions

m
Line 129:
=={{header|Fortran}}==
In ISO Fortran 90 or later, use the SUM intrinsic, the SIZE intrinsic and the MAX intrinsic (to avoid divide by zero):
REALreal, TARGETtarget, DIMENSIONdimension(100) :: Aa = (/ (i, i=1, 100) /)
REALreal, DIMENSIONdimension(5,20) :: Bb = RESHAPEreshape( Aa, (/ 5,20 /) )
REALreal, POINTERpointer, DIMENSIONdimension(:) :: Pp => Aa(2:1) ! pointer to zero-length array
REALreal :: MEANmean, ZMEANzmean, BMEANbmean
REALreal, DIMENSIONdimension(20) :: COLMEANScolmeans
REALreal, DIMENSIONdimension(5) :: ROWMEANSrowmeans
MEANmean = SUMsum(Aa)/SIZEsize(Aa) ! SUM of A's elements divided by SIZE of A
MEANmean = SUMsum(Aa)/MAXmax(SIZEsize(Aa),1) ! Same result, but safer code
! MAX of SIZE and 1 prevents divide by zero if SIZE == 0 (zero-length array)
ZMEANzmean = SUMsum(Pp)/MAXmax(SIZEsize(Pp),1) ! Here the safety check pays off. Since P is a zero-length array,
! expression becomes "0 / MAX( 0, 1 ) -> 0 / 1 -> 0", rather than "0 / 0 -> NaN"
BMEANbmean = SUMsum(Bb)/MAXmax(SIZEsize(Bb),1) ! multidimensional SUM over multidimensional SIZE
ROWMEANSrowmeans = SUMsum(Bb,1)/MAXmax(SIZEsize(Bb,2),1) ! SUM elements in each row (dimension 1)
! dividing by the length of the row, which is the number of columns (SIZE of dimension 2)
COLMEANScolmeans = SUMsum(Bb,2)/MAXmax(SIZEsize(Bb,1),1) ! SUM elements in each column (dimension 2)
! dividing by the length of the column, which is the number of rows (SIZE of dimension 1)
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.