From 53f69e7c6ffa43cc8e7baf8ab966053abab8684e Mon Sep 17 00:00:00 2001 From: Max Ghenis <6076111+MaxGhenis@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:47:52 -0500 Subject: [PATCH 1/6] Correct the Gini coefficient for unequal survey weights --- changelog.d/527.fixed.md | 1 + src/policyengine/outputs/inequality.py | 18 ++---- tests/test_inequality_properties.py | 89 ++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 12 deletions(-) create mode 100644 changelog.d/527.fixed.md create mode 100644 tests/test_inequality_properties.py diff --git a/changelog.d/527.fixed.md b/changelog.d/527.fixed.md new file mode 100644 index 000000000..0aff23927 --- /dev/null +++ b/changelog.d/527.fixed.md @@ -0,0 +1 @@ +Correct Gini coefficients for unequal survey weights so replicating or splitting weighted rows preserves the result. diff --git a/src/policyengine/outputs/inequality.py b/src/policyengine/outputs/inequality.py index 4b16f7a97..cde00174d 100644 --- a/src/policyengine/outputs/inequality.py +++ b/src/policyengine/outputs/inequality.py @@ -36,24 +36,18 @@ def _gini(values: np.ndarray, weights: np.ndarray) -> float: sorted_values = values[sorted_indices] sorted_weights = weights[sorted_indices] - # Cumulative weights and weighted values cumulative_weights = np.cumsum(sorted_weights) total_weight = cumulative_weights[-1] - cumulative_weighted_values = np.cumsum(sorted_values * sorted_weights) - total_weighted_value = cumulative_weighted_values[-1] + total_weighted_value = np.sum(sorted_values * sorted_weights) if total_weighted_value == 0: return 0.0 - # Calculate Gini using the area formula - # Gini = 1 - 2 * (area under Lorenz curve) - lorenz_curve = cumulative_weighted_values / total_weighted_value - weight_fractions = sorted_weights / total_weight - - # Area under Lorenz curve using trapezoidal rule - area = np.sum(weight_fractions * (lorenz_curve - weight_fractions / 2)) - - return float(1 - 2 * area) + # Each income gap contributes to pairs with one row on either side. + lower_weight_fractions = cumulative_weights[:-1] / total_weight + upper_weights = np.cumsum(sorted_weights[:0:-1])[::-1] + weighted_gaps = np.diff(sorted_values) * lower_weight_fractions * upper_weights + return float(np.sum(weighted_gaps) / total_weighted_value) def _series_for_entity( diff --git a/tests/test_inequality_properties.py b/tests/test_inequality_properties.py new file mode 100644 index 000000000..e838be51f --- /dev/null +++ b/tests/test_inequality_properties.py @@ -0,0 +1,89 @@ +"""Properties of the survey-weighted Gini coefficient.""" + +import numpy as np +import pytest +from hypothesis import given +from hypothesis import strategies as st + +from policyengine.outputs.inequality import _gini + +INCOMES = st.floats(min_value=0, max_value=10_000, allow_subnormal=False) +WEIGHTS = st.floats(min_value=0.125, max_value=32) + + +@st.composite +def weighted_incomes(draw, incomes=INCOMES, weights=WEIGHTS): + rows = draw(st.lists(st.tuples(incomes, weights), min_size=1, max_size=16)) + values, row_weights = zip(*rows) + return np.array(values, dtype=float), np.array(row_weights) + + +@given(weighted_incomes(weights=st.integers(min_value=1, max_value=10))) +def test_gini_integer_weights_match_unit_weight_copies(sample): + values, weights = sample + replicated = np.repeat(values, weights) + + assert _gini(values, weights) == pytest.approx( + _gini(replicated, np.ones_like(replicated)), abs=1e-12, rel=0 + ) + + +@given(weighted_incomes(), st.floats(min_value=0.125, max_value=0.875)) +def test_gini_is_invariant_to_splitting_a_weight(sample, fraction): + values, weights = sample + first_weight = weights[0] * fraction + split_values = np.insert(values, 0, values[0]) + split_weights = np.insert(weights, 0, first_weight) + split_weights[1] -= first_weight + + assert _gini(split_values, split_weights) == pytest.approx( + _gini(values, weights), abs=1e-12, rel=0 + ) + + +@given( + weighted_incomes( + incomes=st.integers(min_value=0, max_value=10_000), + weights=st.integers(min_value=1, max_value=32), + ) +) +def test_gini_is_in_range(sample): + # Small integers avoid estimator-dependent roundoff at exactly zero. + assert 0 <= _gini(*sample) < 1 + + +@pytest.mark.parametrize("scale_income", [True, False], ids=["income", "weight"]) +@given(weighted_incomes(), st.floats(min_value=0.125, max_value=32)) +def test_gini_is_scale_invariant(scale_income, sample, factor): + values, weights = sample + scaled = (values * factor, weights) if scale_income else (values, weights * factor) + + assert _gini(*scaled) == pytest.approx(_gini(values, weights), abs=1e-12, rel=0) + + +@given(weighted_incomes(), st.data()) +def test_gini_is_row_order_invariant(sample, data): + values, weights = sample + order = data.draw(st.permutations(range(len(values)))) + indices = np.array(order) + + assert _gini(values[indices], weights[indices]) == pytest.approx( + _gini(values, weights), abs=1e-12, rel=0 + ) + + +@given(INCOMES, st.lists(WEIGHTS, min_size=1, max_size=16)) +def test_gini_is_zero_for_equal_incomes(income, weights): + assert _gini(np.full(len(weights), income), np.array(weights)) == pytest.approx( + 0, abs=1e-12, rel=0 + ) + + +@given(WEIGHTS, WEIGHTS) +def test_gini_equals_zero_income_population_share(zero_weight, positive_weight): + weights = np.array([zero_weight, positive_weight]) + expected = zero_weight / weights.sum() + + assert _gini(np.array([0.0, 1.0]), weights) == pytest.approx( + expected, abs=1e-12, rel=0 + ) From 2c68350f09e72a03e50f34142c1afe54389b444b Mon Sep 17 00:00:00 2001 From: Max Ghenis <6076111+MaxGhenis@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:34:33 -0500 Subject: [PATCH 2/6] Prevent integer overflow in weighted Gini income gaps --- src/policyengine/outputs/inequality.py | 4 ++++ tests/test_inequality_properties.py | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/policyengine/outputs/inequality.py b/src/policyengine/outputs/inequality.py index cde00174d..0cd47233c 100644 --- a/src/policyengine/outputs/inequality.py +++ b/src/policyengine/outputs/inequality.py @@ -36,6 +36,10 @@ def _gini(values: np.ndarray, weights: np.ndarray) -> float: sorted_values = values[sorted_indices] sorted_weights = weights[sorted_indices] + # Promote incomes before computing products and differences. + sorted_values = sorted_values.astype( + np.result_type(values.dtype, np.float64), copy=False + ) cumulative_weights = np.cumsum(sorted_weights) total_weight = cumulative_weights[-1] total_weighted_value = np.sum(sorted_values * sorted_weights) diff --git a/tests/test_inequality_properties.py b/tests/test_inequality_properties.py index e838be51f..c1c01662d 100644 --- a/tests/test_inequality_properties.py +++ b/tests/test_inequality_properties.py @@ -87,3 +87,16 @@ def test_gini_equals_zero_income_population_share(zero_weight, positive_weight): assert _gini(np.array([0.0, 1.0]), weights) == pytest.approx( expected, abs=1e-12, rel=0 ) + + +def test_gini_handles_income_gaps_larger_than_integer_dtype(): + values = np.array([-10_000, 25_000, 25_000], dtype=np.int16) + + assert _gini(values, np.ones(3)) == pytest.approx(7 / 12) + + +def test_gini_with_multiple_weighted_income_gaps(): + values = np.array([0.0, 1.0, 10.0]) + weights = np.array([5.0, 3.0, 2.0]) + + assert _gini(values, weights) == pytest.approx(169 / 230) From 728ccf50222c7e9c3d4a5aa7aa6829642122cc18 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 1 Dec 2026 06:58:57 -0500 Subject: [PATCH 3/6] Preserve the weighted Gini when signed incomes nearly cancel Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- changelog.d/527.fixed.md | 2 +- src/policyengine/outputs/inequality.py | 38 +++++++++++++++- tests/test_inequality.py | 12 ++++++ tests/test_inequality_properties.py | 60 +++++++++++++++++++++++++- 4 files changed, 108 insertions(+), 4 deletions(-) diff --git a/changelog.d/527.fixed.md b/changelog.d/527.fixed.md index 0aff23927..f5ee7708e 100644 --- a/changelog.d/527.fixed.md +++ b/changelog.d/527.fixed.md @@ -1 +1 @@ -Correct Gini coefficients for unequal survey weights so replicating or splitting weighted rows preserves the result. +Correct the survey-weighted Gini coefficient by weighting each income gap by the survey population on either side. diff --git a/src/policyengine/outputs/inequality.py b/src/policyengine/outputs/inequality.py index 0cd47233c..e763f8937 100644 --- a/src/policyengine/outputs/inequality.py +++ b/src/policyengine/outputs/inequality.py @@ -1,6 +1,8 @@ """Inequality analysis output types.""" from enum import Enum +from itertools import chain +from math import fsum from typing import Any, Optional, Union import numpy as np @@ -17,6 +19,35 @@ class USInequalityPreset(str, Enum): CBO_COMPARABLE = "cbo_comparable" +def _weighted_income_total( + values: np.ndarray, weights: np.ndarray +) -> float | np.floating: + products = values * weights + total = products.sum() + if products.dtype != np.float64 or not np.isfinite(total): + return total + + # Allow for one product rounding and up to one addition per row. + error_bound = np.finfo(np.float64).eps * products.size * np.abs(products).sum() + if not 0 < error_bound < np.inf or abs(total) > error_bound: + return total + + # Split each mantissa into two parts of at most 26 significant bits. + # Sum the exact partial products to recover the total after cancellation. + mantissas, exponents = np.frexp(np.stack((values, weights))) + high = np.ldexp(np.rint(np.ldexp(mantissas, 26)), -26) + income_high, weight_high = high + income_low, weight_low = mantissas - high + product_exponents = exponents[0] + exponents[1] + return fsum( + chain.from_iterable( + np.ldexp(income_part * weight_part, product_exponents).tolist() + for income_part in (income_high, income_low) + for weight_part in (weight_high, weight_low) + ) + ) + + def _gini(values: np.ndarray, weights: np.ndarray) -> float: """Calculate weighted Gini coefficient. @@ -25,7 +56,10 @@ def _gini(values: np.ndarray, weights: np.ndarray) -> float: weights: Array of weights Returns: - Gini coefficient between 0 (perfect equality) and 1 (perfect inequality) + The weighted Gini coefficient. For nonnegative incomes and survey + weights with positive totals, the mathematical coefficient lies in + [0, 1]. Signed incomes can give a value outside that interval. Empty + inputs, zero total weight, and zero weighted income return 0.0. """ # Handle edge cases if len(values) == 0 or weights.sum() == 0: @@ -42,7 +76,7 @@ def _gini(values: np.ndarray, weights: np.ndarray) -> float: ) cumulative_weights = np.cumsum(sorted_weights) total_weight = cumulative_weights[-1] - total_weighted_value = np.sum(sorted_values * sorted_weights) + total_weighted_value = _weighted_income_total(sorted_values, sorted_weights) if total_weighted_value == 0: return 0.0 diff --git a/tests/test_inequality.py b/tests/test_inequality.py index f7ef6ee47..1de46f7c4 100644 --- a/tests/test_inequality.py +++ b/tests/test_inequality.py @@ -16,6 +16,7 @@ Inequality, USInequalityPreset, _gini, + calculate_uk_inequality, calculate_us_inequality, ) from policyengine.tax_benefit_models.uk import ( @@ -43,6 +44,17 @@ def _make_household_simulation(household_df: pd.DataFrame) -> Simulation: ) +def test_uk_inequality_gini_is_zero_when_weighted_incomes_cancel(): + households = pd.DataFrame( + { + UK_INEQUALITY_INCOME_VARIABLE: [-11, 0, 0, 0, 0, 0, 4, 7], + "household_weight": [0.01] * 8, + } + ) + + assert calculate_uk_inequality(_make_household_simulation(households)).gini == 0.0 + + def test_gini_perfect_equality(): """Test Gini coefficient with perfect equality (all same income).""" values = np.array([100.0, 100.0, 100.0, 100.0]) diff --git a/tests/test_inequality_properties.py b/tests/test_inequality_properties.py index c1c01662d..104232287 100644 --- a/tests/test_inequality_properties.py +++ b/tests/test_inequality_properties.py @@ -1,8 +1,11 @@ """Properties of the survey-weighted Gini coefficient.""" +from fractions import Fraction +from itertools import combinations + import numpy as np import pytest -from hypothesis import given +from hypothesis import given, settings from hypothesis import strategies as st from policyengine.outputs.inequality import _gini @@ -100,3 +103,58 @@ def test_gini_with_multiple_weighted_income_gaps(): weights = np.array([5.0, 3.0, 2.0]) assert _gini(values, weights) == pytest.approx(169 / 230) + + +@pytest.mark.parametrize("scale", [0.5, 1, 2, 3, 10]) +def test_gini_is_zero_at_each_scale_when_weighted_incomes_cancel(scale): + assert _gini(scale * np.array([-3, 1, 2]), np.full(3, 0.01)) == 0.0 + + +def test_gini_is_zero_after_splitting_a_weight_when_weighted_incomes_cancel(): + assert _gini(np.array([-2, 1, 1]), np.full(3, 0.01)) == 0.0 + assert _gini(np.array([-2, 1, 1, 1]), np.array([0.01, 0.005, 0.005, 0.01])) == 0.0 + + +def _exact_gini(values, weights): + rows = list(zip(map(Fraction, values.tolist()), map(Fraction, weights.tolist()))) + total_weight = sum(weight for _, weight in rows) + total_income = sum(value * weight for value, weight in rows) + if total_weight == 0 or total_income == 0: + return Fraction(0) + + pairwise_differences = sum( + left_weight * right_weight * abs(left - right) + for (left, left_weight), (right, right_weight) in combinations(rows, 2) + ) + return pairwise_differences / (total_weight * total_income) + + +@pytest.mark.parametrize("direction", [-np.inf, np.inf], ids=["negative", "positive"]) +def test_gini_preserves_a_small_nonzero_weighted_income(direction): + values = np.array([-3, 1, np.nextafter(2.0, direction)]) + weights = np.full(3, 0.01) + expected = float(_exact_gini(values, weights)) + + assert _gini(values, weights) == pytest.approx(expected, rel=1e-12) + + +@settings(deadline=None) +@given(st.lists(st.tuples(st.integers(-10, 10), st.integers(0, 5)), max_size=10)) +def test_gini_matches_exact_pairwise_oracle(rows): + values, weights = np.array(rows, dtype=int).reshape(-1, 2).T + expected = float(_exact_gini(values, weights)) + replicated_values = np.repeat(values, weights) + samples = [(values, weights), (replicated_values, np.ones_like(replicated_values))] + if rows: + middle = len(rows) // 2 + half_weight = weights[middle] / 2 + split_values = np.insert(values, middle, values[middle]) + split_weights = np.insert(weights.astype(float), middle, half_weight) + split_weights[middle + 1] = half_weight + samples.append((split_values, split_weights)) + + for sample in samples: + if expected == 0: + assert _gini(*sample) == 0.0 + else: + assert _gini(*sample) == pytest.approx(expected, rel=1e-12, abs=0) From 2cee69b61464211a68693aca73765e32f86b8493 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 16:02:28 -0500 Subject: [PATCH 4/6] Sum Gini weighted totals and gaps exactly when floats cancel or overflow Round 3 found that recomputing a cancelled total could erase a nonzero subnormal result, and that finite sentinel inputs overflowed the public helper. The weighted total now sums exact integer products and rounds once, and the weighted-gap ratio is exact for extreme finite inputs. Tests cover the subnormal total, both overflow sentinels and the unequal-weight cancellation case. Co-Authored-By: Claude Opus 5.5 --- src/policyengine/outputs/inequality.py | 107 +++++++++++++++++++------ tests/test_inequality.py | 44 ++++++++++ tests/test_inequality_properties.py | 34 +++++++- 3 files changed, 161 insertions(+), 24 deletions(-) diff --git a/src/policyengine/outputs/inequality.py b/src/policyengine/outputs/inequality.py index e763f8937..0a3a48b6d 100644 --- a/src/policyengine/outputs/inequality.py +++ b/src/policyengine/outputs/inequality.py @@ -1,8 +1,7 @@ """Inequality analysis output types.""" from enum import Enum -from itertools import chain -from math import fsum +from itertools import pairwise from typing import Any, Optional, Union import numpy as np @@ -19,33 +18,81 @@ class USInequalityPreset(str, Enum): CBO_COMPARABLE = "cbo_comparable" +_FLOAT64 = np.finfo(np.float64) + + +def _dyadic_integers(values: np.ndarray) -> tuple[list[int], int]: + """Express finite binary floats as integers over a common denominator.""" + ratios = [value.as_integer_ratio() for value in values.tolist()] + denominator = max((divisor for _, divisor in ratios), default=1) + integers = [numerator * (denominator // divisor) for numerator, divisor in ratios] + return integers, denominator + + +def _ratio_as_float(numerator: int, denominator: int) -> float: + try: + return numerator / denominator + except OverflowError: + return float("-inf") if (numerator < 0) != (denominator < 0) else float("inf") + + def _weighted_income_total( values: np.ndarray, weights: np.ndarray ) -> float | np.floating: - products = values * weights - total = products.sum() - if products.dtype != np.float64 or not np.isfinite(total): + total: np.floating + if np.result_type(values, weights) != np.float64: + total = (values * weights).sum() return total - # Allow for one product rounding and up to one addition per row. - error_bound = np.finfo(np.float64).eps * products.size * np.abs(products).sum() - if not 0 < error_bound < np.inf or abs(total) > error_bound: - return total + with np.errstate(over="ignore", under="ignore", invalid="ignore"): + products = values * weights + total = products.sum() + if products.size == 0: + return total + absolute_total = float(np.abs(products).sum()) - # Split each mantissa into two parts of at most 26 significant bits. - # Sum the exact partial products to recover the total after cancellation. - mantissas, exponents = np.frexp(np.stack((values, weights))) - high = np.ldexp(np.rint(np.ldexp(mantissas, 26)), -26) - income_high, weight_high = high - income_low, weight_low = mantissas - high - product_exponents = exponents[0] + exponents[1] - return fsum( - chain.from_iterable( - np.ldexp(income_part * weight_part, product_exponents).tolist() - for income_part in (income_high, income_low) - for weight_part in (weight_high, weight_low) - ) + # Allow for product and addition rounding, including subnormal products. + error_bound = products.size * ( + float(_FLOAT64.eps) * absolute_total + float(_FLOAT64.smallest_subnormal) ) + if abs(total) > error_bound or ( + absolute_total == 0 and not np.any((values != 0) & (weights != 0)) + ): + return total + if not (np.isfinite(values).all() and np.isfinite(weights).all()): + return total + + # Keep the exact exponents through multiplication and summation. + incomes, income_denominator = _dyadic_integers(values) + row_weights, weight_denominator = _dyadic_integers(weights) + numerator = sum(income * weight for income, weight in zip(incomes, row_weights)) + return _ratio_as_float(numerator, income_denominator * weight_denominator) + + +def _outside_fast_gini_range(values: np.ndarray) -> bool: + # Values in this range are multiples of 2**-152. This leaves room in + # binary64 for gaps, weight fractions and products over up to 2**63 rows. + magnitudes = np.abs(values) + outside = (magnitudes > 2.0**100) | ((magnitudes < 2.0**-100) & (magnitudes != 0)) + return bool(outside.any()) + + +def _exact_gini(sorted_values: np.ndarray, sorted_weights: np.ndarray) -> float: + # The common scales cancel from the Gini ratio. Integer gaps and weight + # sums let us defer rounding until the final division. + values, _ = _dyadic_integers(sorted_values) + weights, _ = _dyadic_integers(sorted_weights) + total_weight = sum(weights) + total_income = sum(value * weight for value, weight in zip(values, weights)) + if total_weight == 0 or total_income == 0: + return 0.0 + + lower_weight = 0 + weighted_gaps = 0 + for weight, (lower, upper) in zip(weights, pairwise(values)): + lower_weight += weight + weighted_gaps += (upper - lower) * lower_weight * (total_weight - lower_weight) + return _ratio_as_float(weighted_gaps, total_weight * total_income) def _gini(values: np.ndarray, weights: np.ndarray) -> float: @@ -62,7 +109,7 @@ def _gini(values: np.ndarray, weights: np.ndarray) -> float: inputs, zero total weight, and zero weighted income return 0.0. """ # Handle edge cases - if len(values) == 0 or weights.sum() == 0: + if len(values) == 0: return 0.0 # Sort by values @@ -74,6 +121,20 @@ def _gini(values: np.ndarray, weights: np.ndarray) -> float: sorted_values = sorted_values.astype( np.result_type(values.dtype, np.float64), copy=False ) + if ( + sorted_values.dtype == sorted_weights.dtype == np.float64 + and ( + _outside_fast_gini_range(sorted_values) + or _outside_fast_gini_range(sorted_weights) + ) + and np.isfinite(sorted_values).all() + and np.isfinite(sorted_weights).all() + ): + return _exact_gini(sorted_values, sorted_weights) + + if weights.sum() == 0: + return 0.0 + cumulative_weights = np.cumsum(sorted_weights) total_weight = cumulative_weights[-1] total_weighted_value = _weighted_income_total(sorted_values, sorted_weights) diff --git a/tests/test_inequality.py b/tests/test_inequality.py index 1de46f7c4..63a5f575f 100644 --- a/tests/test_inequality.py +++ b/tests/test_inequality.py @@ -16,6 +16,7 @@ Inequality, USInequalityPreset, _gini, + _weighted_income_total, calculate_uk_inequality, calculate_us_inequality, ) @@ -55,6 +56,49 @@ def test_uk_inequality_gini_is_zero_when_weighted_incomes_cancel(): assert calculate_uk_inequality(_make_household_simulation(households)).gini == 0.0 +def test_uk_inequality_gini_preserves_a_subnormal_weighted_income_total(): + smallest_subnormal = 2.0**-1074 + income = 2.0**-1020 + small_weight = 2.0**-56 + values = np.array( + [ + -income, + income, + 2 * income - 8 * smallest_subnormal, + 2 * income + 8 * smallest_subnormal, + ] + ) + weights = np.array([1.0, 1.0, small_weight, small_weight]) + households = pd.DataFrame( + {UK_INEQUALITY_INCOME_VARIABLE: values, "household_weight": weights} + ) + + assert _weighted_income_total(values, weights) == smallest_subnormal + assert calculate_uk_inequality(_make_household_simulation(households)).gini == 2**54 + + +@pytest.mark.parametrize( + ("unit_incomes", "weights", "expected"), + [([-1.0, 1.0], [0.25, 0.5], 4 / 3), ([0.0, 1.0], [2.0, 2.0], 0.5)], + ids=["income-gap", "weighted-income"], +) +def test_uk_inequality_gini_with_income_sentinels(unit_incomes, weights, expected): + households = pd.DataFrame( + { + "custom_income": np.array(unit_incomes) * np.finfo(np.float64).max, + "household_weight": weights, + } + ) + + # Income shares still use the original weighted-income products. + with np.errstate(over="ignore", invalid="ignore"): + result = calculate_uk_inequality( + _make_household_simulation(households), income_variable="custom_income" + ) + + assert result.gini == pytest.approx(expected, rel=1e-15, abs=0) + + def test_gini_perfect_equality(): """Test Gini coefficient with perfect equality (all same income).""" values = np.array([100.0, 100.0, 100.0, 100.0]) diff --git a/tests/test_inequality_properties.py b/tests/test_inequality_properties.py index 104232287..67779d0b1 100644 --- a/tests/test_inequality_properties.py +++ b/tests/test_inequality_properties.py @@ -8,7 +8,7 @@ from hypothesis import given, settings from hypothesis import strategies as st -from policyengine.outputs.inequality import _gini +from policyengine.outputs.inequality import _gini, _weighted_income_total INCOMES = st.floats(min_value=0, max_value=10_000, allow_subnormal=False) WEIGHTS = st.floats(min_value=0.125, max_value=32) @@ -115,6 +115,19 @@ def test_gini_is_zero_after_splitting_a_weight_when_weighted_incomes_cancel(): assert _gini(np.array([-2, 1, 1, 1]), np.array([0.01, 0.005, 0.005, 0.01])) == 0.0 +def test_gini_is_zero_when_distinct_incomes_and_unequal_weights_cancel(): + assert _gini(np.array([-3.0, 1.0, 4.0]), np.array([0.01, 0.01, 0.005])) == 0.0 + + +def test_gini_retains_weighted_income_sign_when_products_underflow(): + smallest_subnormal = 2.0**-1074 + values = np.array([-smallest_subnormal] * 4 + [smallest_subnormal]) + weights = np.array([0.5] * 4 + [0.75]) + + assert _weighted_income_total(values, weights) == -smallest_subnormal + assert _gini(values, weights) == pytest.approx(-48 / 55, rel=1e-15, abs=0) + + def _exact_gini(values, weights): rows = list(zip(map(Fraction, values.tolist()), map(Fraction, weights.tolist()))) total_weight = sum(weight for _, weight in rows) @@ -129,6 +142,25 @@ def _exact_gini(values, weights): return pairwise_differences / (total_weight * total_income) +@pytest.mark.parametrize( + ("values", "weights"), + [ + ([-9.9792015476736e291, np.finfo(np.float64).max], [1.0, 1.0]), + ([0.0, 1.0], [2.0**1023] * 2), + ([0.0, 4.0], [2.0**1022] * 2), + ([-np.finfo(np.float64).max, 4.0, np.finfo(np.float64).max], [1.0] * 3), + ], + ids=["income-gap", "weight-sum", "weighted-income", "absolute-income-sum"], +) +def test_gini_matches_pairwise_oracle_for_extreme_finite_values(values, weights): + values = np.array(values) + weights = np.array(weights) + expected = float(_exact_gini(values, weights)) + + with np.errstate(over="raise", invalid="raise"): + assert _gini(values, weights) == pytest.approx(expected, rel=1e-15, abs=0) + + @pytest.mark.parametrize("direction", [-np.inf, np.inf], ids=["negative", "positive"]) def test_gini_preserves_a_small_nonzero_weighted_income(direction): values = np.array([-3, 1, np.nextafter(2.0, direction)]) From f9b9f04e634137fe21e13dd21ec51e0eae73cd4f Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 16:40:40 -0500 Subject: [PATCH 5/6] Test the overflow branch of the weighted income total directly The public Gini sentinels reach the exact pairwise path before this function runs, so its overflow branch had no test. Direct asserts now check that cancelling maximum-float products sum to 4 exactly, and that products overflowing in one direction give plus or minus infinity. Co-Authored-By: Claude Opus 5.5 --- tests/test_inequality_properties.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/test_inequality_properties.py b/tests/test_inequality_properties.py index 67779d0b1..11f8fa3f0 100644 --- a/tests/test_inequality_properties.py +++ b/tests/test_inequality_properties.py @@ -128,6 +128,14 @@ def test_gini_retains_weighted_income_sign_when_products_underflow(): assert _gini(values, weights) == pytest.approx(-48 / 55, rel=1e-15, abs=0) +def test_weighted_income_total_sums_exactly_when_products_overflow(): + largest = np.finfo(np.float64).max + + assert _weighted_income_total(np.array([-largest, 4.0, largest]), np.ones(3)) == 4.0 + assert _weighted_income_total(np.array([largest, largest]), np.ones(2)) == np.inf + assert _weighted_income_total(np.array([-largest, -largest]), np.ones(2)) == -np.inf + + def _exact_gini(values, weights): rows = list(zip(map(Fraction, values.tolist()), map(Fraction, weights.tolist()))) total_weight = sum(weight for _, weight in rows) From 161977b5621f0f0d392ba56665650793b57a36cd Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 22:28:11 -0500 Subject: [PATCH 6/6] Name the overflow test after the reductions it exercises Every case uses unit weights, so only the sums overflow. Co-Authored-By: Claude Opus 5.5 --- tests/test_inequality_properties.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_inequality_properties.py b/tests/test_inequality_properties.py index 11f8fa3f0..c61b9baad 100644 --- a/tests/test_inequality_properties.py +++ b/tests/test_inequality_properties.py @@ -128,7 +128,7 @@ def test_gini_retains_weighted_income_sign_when_products_underflow(): assert _gini(values, weights) == pytest.approx(-48 / 55, rel=1e-15, abs=0) -def test_weighted_income_total_sums_exactly_when_products_overflow(): +def test_weighted_income_total_sums_exactly_when_reductions_overflow(): largest = np.finfo(np.float64).max assert _weighted_income_total(np.array([-largest, 4.0, largest]), np.ones(3)) == 4.0