diff --git a/quantecon/_inequality.py b/quantecon/_inequality.py index 293f1555..952787e6 100644 --- a/quantecon/_inequality.py +++ b/quantecon/_inequality.py @@ -4,7 +4,7 @@ """ import numpy as np -from numba import njit, prange +from numba import njit @njit @@ -54,7 +54,7 @@ def lorenz_curve(y): return cum_people, cum_income -@njit(parallel=True) +@njit def gini_coefficient(y): r""" Implements the Gini inequality index @@ -76,11 +76,13 @@ def gini_coefficient(y): https://en.wikipedia.org/wiki/Gini_coefficient """ n = len(y) - i_sum = np.zeros(n) - for i in prange(n): - for j in range(n): - i_sum[i] += abs(y[i] - y[j]) - return np.sum(i_sum) / (2 * n * np.sum(y)) + y_s = np.sort(y) + i_weighted = 0.0 + total = 0.0 + for i in range(n): + i_weighted += (i + 1) * y_s[i] + total += y_s[i] + return (2 * i_weighted) / (n * total) - (n + 1) / n def shorrocks_index(A): @@ -152,4 +154,3 @@ def rank_size(data, c=1.0): rank_data = np.arange(len(w)) + 1 size_data = w return rank_data, size_data - diff --git a/quantecon/tests/test_inequality.py b/quantecon/tests/test_inequality.py index be682396..0aa968cb 100644 --- a/quantecon/tests/test_inequality.py +++ b/quantecon/tests/test_inequality.py @@ -59,6 +59,11 @@ def test_gini_coeff(): coeff = gini_coefficient(y) assert_allclose(expected, coeff, rtol=1e-01) + # Regression against the pairwise definition + y = np.array([1.0, 2.0, 4.0, 8.0]) + expected = np.abs(y[:, None] - y).sum() / (2 * len(y) * y.sum()) + assert_allclose(expected, gini_coefficient(y)) + # Tests Weibull: G = 1 - 2**(-1/a) a = np.random.randint(2, 15) expected = 1 - 2 ** (-1 / a) @@ -130,4 +135,3 @@ def test_rank_size(): r_sqval_exp = r_value_exp**2 assert_raises(AssertionError, assert_allclose, r_sqval_exp, 1, rtol=1e-3) -