Clicky

Fortran Wiki
Quartiles

program quartile
! Fortran program to test the 3 methods of Quartile Calculation.
! Quartiles are calculated differently in EXCEL, Minitab and SAS method 5
! This program tests the 3 methods.
! by Sukhbinder Singh (aerogeek)
! Background info http://sukhbinder.wordpress.com/2011/01/22/fortran-program-to-calculate-quartiles-as-calculated-by-minitab-and-excel/ 

implicit none
interface
 subroutine sasm5(x,quart)
  real*8 :: x(:),quart
 end subroutine

 subroutine sasm4(x,quart)
  real*8 :: x(:),quart
 end subroutine

 subroutine excel(x,quart)
  real*8 :: x(:),quart
 end subroutine
end interface

real*8 :: a,b,c,x(4),quart
data x/1.0d0,2.0d0,3.0d0,4.0d0/

Print *, "Excel Method"
quart=0.25d0
call excel(x,quart)
print *,'  q1=',quart

quart=0.500d0
call excel(x,quart)
print *,'  Median=',quart

quart=0.750d0
call excel(x,quart)
print *,'  q3=',quart



Print *, "Minitab Method"
quart=0.25d0
call sasm4(x,quart)
print *,'  q1=',quart

quart=0.500d0
call sasm4(x,quart)
print *,'  Median=',quart

quart=0.750d0
call sasm4(x,quart)
print *,'  q3=',quart


Print *, "SAS Method 5"
quart=0.25d0
call sasm5(x,quart)
print *,'  q1=',quart

quart=0.500d0
call sasm5(x,quart)
print *,'  Median=',quart

quart=0.750d0
call sasm5(x,quart)
print *,'  q3=',quart


end

subroutine excel(x,quart)
implicit none
! Excel's method to calculate quartiles.
! Based on discussion in this paper http://www.haiweb.org/medicineprices/manual/quartiles_iTSS.pdf
!

real*8 :: x(:),quart,a,b,c
integer :: n,ib

n=size(x)

a=(n-1)*quart
call getgp(a,b,c)

ib=int(c)
!print *,n,a,b,c,ib


quart= (1-b)*x(ib+1) +b*x(ib+2)

end 

subroutine sasm4(x,quart)
implicit none
! Minitab’s method of calculating is the same as the SAS Method 4.
! Based on discussion in this paper http://www.haiweb.org/medicineprices/manual/quartiles_iTSS.pdf
!

real*8 :: x(:),quart,a,b,c
integer :: n,ib


n=size(x)

a=(n+1)*quart
call getgp(a,b,c)

ib=int(c)
!print *,n,a,b,c,ib

if((ib+1)>n) then
quart=(1-b)*x(ib) +b*x(n)
else
quart=(1-b)*x(ib) +b*x(ib+1)
end if

end 


subroutine sasm5(x,quart)
! Calculate Quartiles using SAS Method 5
! This method is the default method of SAS and is based on the empirical distribution function. 
! Based on discussion in this paper http://www.haiweb.org/medicineprices/manual/quartiles_iTSS.pdf
!
implicit none
real*8 :: x(:),quart,a,b,c,tol,diff
integer :: n,ib

tol=1.e-8
n=size(x)

a=n*quart
call getgp(a,b,c)

ib=int(c)
!print *,n,a,b,c,ib

diff=b-0.0d0
if(diff <=tol) then
  quart=(x(ib+1)+x(ib))/2.0d0
else
 quart=x(ib+1)
end if

end 

subroutine getgp(a,b,c)
! Subroutine to that returns the Right hand and Left hand side digits of a decimal number
real*8 :: a,b,c

b=mod(a,1.0d0)
c=a-b

end

category: code

Background here