When I write following code with reduce method, values are imprecise:
return bytes.reduce((accumulator, currentValue, index) => {
return accumulator + (currentValue * Math.pow(256,(bytes.length - 2) - index));
}
)
eg. output numbers 5.99609375, 10.99609375, 7.99609375, 14.99609375
But when I write following code result is precise:
let result = 0.0;
for (let i = 0; i < bytes.length - 1; ++i) {
result = result + (bytes[i] * Math.pow(256, (bytes.length - 2) - i));
}
return result
eg. output numbers 5, 10, 7, 14
Input byte arrays are:
Uint8Array(4) [0, 0, 5, 255]
Uint8Array(4) [0, 0, 10, 255]
Uint8Array(4) [0, 0, 7, 255]
Uint8Array(4) [0, 0, 14, 255]
Why is that? Is there a way to make reduce method work precisely?
const res = document.getElementById('result');
const res2 = document.getElementById('result2');
const arr = a = [
[0, 0, 5, 255],
[0, 0, 10, 255],
[0, 0, 7, 255],
[0, 0, 14, 255]
];
const fn = (bytes) => {
let result = 0.0;
for (let i = 0; i < bytes.length - 1; ++i) {
result = result + (bytes[i] * Math.pow(256, (bytes.length - 2) - i));
}
return result
}
fn2 = (bytes) => {
return bytes.reduce((accumulator, currentValue, index) => {
return accumulator + (currentValue * Math.pow(256, (bytes.length - 2) - index));
})
}
res.innerText += `${arr.map(fn)}`;
res2.innerText += `${arr.map(fn2)}`;
<div id="result"></div>
<div id="result2"></div>