Skip to content

Instantly share code, notes, and snippets.

@harunorimurata
Last active October 7, 2024 10:31
Show Gist options
  • Save harunorimurata/2c7d01d5d48ec5cfdef47a5920199d83 to your computer and use it in GitHub Desktop.
Save harunorimurata/2c7d01d5d48ec5cfdef47a5920199d83 to your computer and use it in GitHub Desktop.
// Kahan-Babuska algorithm
export const sum = (x: number[]) => {
if (x.length === 0) return 0
let res = x[0], c = 0, t = 0
for (let i = 1; i < x.length; i++) {
t = res + x[i]
if (Math.abs(res) >= Math.abs(x[i])) {
c += res - t + x[i]
} else {
c += x[i] - t + res
}
res = t
}
return res + c
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment