JSFiddle - React, Tailwind, and code Playground
HTML
<pre id="output"></pre>
JavaScript
function cascadeRounding(array) {
/*
Given an array of floats that sum to an integer, this rounds the floats
and returns an array of integers with the same sum.
*/
fpTotal = 0
intTotal = 0
roundedArray = []
array.forEach(function(float, index) {
integer = Math.round( float + fpTotal ) - intTotal
fpTotal += float
intTotal += integer
roundedArray.push(integer)
} )
/*
Some proofs
*/
sum = 0
array.forEach(function(num){
sum += num
})
out("Input: " + array)
out("Input's sum: " + sum)
sum = 0
roundedArray.forEach(function(num){
sum += num
})
out("Output: " + roundedArray)
out("Output's sum: " + sum)
return roundedArray
}
function out() {
var args = Array.prototype.slice.call(arguments, 0);
document.getElementById('output').innerHTML += args.join(" ") + "\n";
}
cascadeRounding([3.614594838253174, 3.0347235317252936, 2.9433342851549944, 2.312143628092747, 1.980004561560413, 1.0910965165123099, 0.6642062974676156, 0.3598963412334531])