Skip to content

Fix float32 truncation in balanced_allocation iteration loop (#1203)#1205

Merged
brendancol merged 1 commit into
masterfrom
issue-1203
Apr 15, 2026
Merged

Fix float32 truncation in balanced_allocation iteration loop (#1203)#1205
brendancol merged 1 commit into
masterfrom
issue-1203

Conversation

@brendancol
Copy link
Copy Markdown
Contributor

Closes #1203.

Summary

  • _allocate_biased and _allocate_from_costs cast the allocation array to
    float32 internally. The balancing loop then compared these float32 values
    against float64 source IDs. For non-integer source IDs (e.g. 0.1, 0.3),
    float64 -> float32 -> float64 produces a different value, so alloc == sid
    never matched and the loop exited on the first iteration without balancing.
  • Changed both functions to use float64 for the allocation array. The final
    cast to float32 already happens at the return statement.
  • Added regression test with non-integer source IDs that would fail without
    the fix.

Test plan

  • test_non_integer_source_ids -- three sources with IDs 0.1, 0.3, 0.7
    on a 12x12 grid. Verifies each territory gets at least 20% of cells.
  • All existing test_balanced_allocation.py tests still pass.

_allocate_biased and _allocate_from_costs cast the allocation array to
float32 internally.  The balancing loop then compared these float32
values against float64 source IDs.  For non-integer IDs (e.g. 0.1, 0.3)
the float64->float32->float64 round-trip produces a different value, so
alloc == sid never matched, weights were all zero, and the loop exited
on the first iteration without balancing.

Fix: keep the allocation array as float64 through the iteration loop.
The final cast to float32 happens at the return statement.
@github-actions github-actions Bot added the performance PR touches performance-sensitive code label Apr 15, 2026
@brendancol brendancol merged commit 7d5ea9d into master Apr 15, 2026
11 checks passed
@brendancol brendancol deleted the issue-1203 branch May 4, 2026 13:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance PR touches performance-sensitive code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

balanced_allocation: float32 truncation breaks balancing for non-integer source IDs

1 participant