Fix logic error in balance function

The previous implementation gave uneven weighting to some values.