# Gini coefficient and Lorenz curve

Forums Feedback, suggestions, wishes, etc. Gini coefficient and Lorenz curve

This topic contains 2 replies, has 2 voices, and was last updated by Alessandro Di Nola August 30, 2021 at 11:05 pm.

Viewing 3 posts - 1 through 3 (of 3 total)
• Author
Posts
• #1942

Alessandro Di Nola
User

The toolbox is an excellent resource that makes our life as Fortran programmers much easier. It would be great if in the future the toolbox provides routines to compute the Gini coefficient, Lorenz curve and other widely used measures of concentration.
Thanks!

#1945

Fabian Kindermann
Moderator

Dear Alessandro,

this is a great suggestion. And it is actually only a minor modification as the toolbox already contains a routine for sorting data, which is the most important obstacle when calculating a Gini Index and the like. As a teaser, here would be a quick code for plotting a Lorenz curve and calculating a gini index over the attribute `x_in` with the distribution `y_in`:

``````
function gini(x_in, y_in)

use toolbox

real*8, intent(in) :: x_in(:), y_in(:)
real*8 :: gini
integer :: n, ic
real*8, allocatable :: xs(:), ys(:), xcum(:), ycum(:)
integer, allocatable :: iorder(:)

! get array size
n = size(x_in, 1)

! ALLOCATE LARGE ARRAYS TO AVOID SIZE PROBLEMS

! first deallocate
if(allocated(xs))deallocate(xs)
if(allocated(ys))deallocate(ys)
if(allocated(xcum))deallocate(xcum)
if(allocated(ycum))deallocate(ycum)
if(allocated(iorder))deallocate(iorder)

! then allocate
allocate(xs(n))
allocate(ys(n))
allocate(xcum(0:n))
allocate(ycum(0:n))
allocate(iorder(n))

! NOW CALCULATE GINI INDEX

! sort array
xs = x_in
call sort(xs, iorder)

! sort y's and normalize to 1
do ic = 1, n
ys(ic) = y_in(iorder(ic))
enddo
ys = ys/sum(ys)

! calculate cumulative distributions
xcum(0) = 0d0
ycum(0) = 0d0
do ic = 1, n
xcum(ic) = xcum(ic-1) + ys(ic)*xs(ic)
ycum(ic) = ycum(ic-1) + ys(ic)
enddo

! now normalize cumulated attributes
xcum = xcum/xcum(n)

! plot the Lorenz curve
call plot(ycum, ycum, linewidth=1d0, color="black", dashtype="--")
call plot(ycum, xcum)
call execplot()

! determine gini index
gini = 0d0
do ic = 1, n
gini = gini + ys(ic)*(xcum(ic-1) + xcum(ic))
enddo
gini = 1d0 - gini

end function
``````

Best,
Fabian

• This reply was modified 3 months, 1 week ago by Fabian Kindermann.
• This reply was modified 3 months, 1 week ago by Fabian Kindermann.
#1951

Alessandro Di Nola
User

Dear Fabian,
thanks a lot!

Best,
Alessandro

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.