-1

I used Kahan_summation_algorithm to sum array of floats. Usually it work well, but there is an issue when i try to sum at least two of them 0.1 + 0.2 in js it gives 0.30000000000000004, even when i increase elements in array to force using err variable. Also tested duplication of items and negation them [0.1, 0.2, 0.1, 0.2, -0.1, -0.2] For now i starts using fixed number by multiplying by power of 10, but this is slower and works only when i know precision, i consider to combine those algorithm.

I need working algorithm for summation floats in all cases, in most Kahan algorithm works but for 0.1 nad 0.2 not. Rounding or cutting result number after dot is not acceptable also, because i don't know precision of input numbers or signs

cardiamid
  • 1
  • 2
  • 1
    Welcome to SO, please research and use the search function before asking questions. https://stackoverflow.com/questions/37339683/why-console-log-shows-only-part-of-the-number-resulting-from-0-10-2-0-300000000 – StudioTime Jul 14 '17 at 11:12
  • 1
    Possible duplicate of [Why console.log shows only part of the number resulting from 0.1+0.2=0.30000000000000004](https://stackoverflow.com/questions/37339683/why-console-log-shows-only-part-of-the-number-resulting-from-0-10-2-0-300000000) – StudioTime Jul 14 '17 at 11:12
  • Thanks @DarrenSweeney for your fast replay, read both topics, but those doesn't solves mine. I need working algorithm for summation floats in all cases, in most Kahan algorithm works but for 0.1 nad 0.2 not. Rounding or cutting result number after dot is not acceptable also, because i don't know precision of input number or sign. – cardiamid Jul 14 '17 at 11:54

2 Answers2

0

Found solution on http://0.30000000000000004.com/ page and used http://mikemcl.github.io/decimal.js/ package

cardiamid
  • 1
  • 2
0

This just finds the smallest number given the decimal points and then finds the length of that number to then save as the multiplier. Using the multiplier, I map the whole array as whole numbers by multiplying everything and add using a reduce function. Hope this helps :)

let arr = [0.1, 0.2, 0.1, 0.2, -0.1, -0.2];

//x for array
//y for add or subtract ('+', '-')
function float_arr_sum(x,y){
    //Get biggest number in length form as multiplier
    let lengths = x.map( (a) => a.toString().length );
    let multiplier = 10 ** Math.max(...lengths);
    let result = 0;

    //Multiply every number and add or subtract it from result
    if (y=='+'){
        for(let i = 0; i < x.length; i++){result+=x[i]*multiplier}
    }
    else{
        result = x[0]*multiplier; 
        for(let i = 1; i < x.length; i++){result-=x[i]*multiplier};
    }

    return result / multiplier;
}

console.log(float_arr_sum(arr,'-')); 

P.S - This is an old question but just there for anyone if they have this problem.

Monke
  • 51
  • 6