none
Linq Sum Incorrect Result RRS feed

  • Question

  • I have an double array, then i used linq sum function to total.
    Expect result is 90 but exactly result is 89.999999999999986. Why?

    Here is my code

    double[] arr = new double[]{14.6,11.3,9.5,9.2,9,8.6,5,5,5,4.5,4.5,3.8}

    var sumResult = arr.sum(d=>d);

    expect result is 90

    but when i start break point debug the exactly result is 89.999999999999986




    • Edited by Sovannara Monday, March 18, 2019 4:48 AM
    Monday, March 18, 2019 4:05 AM

Answers

  • I only see 76.999999999999986 when running your code. Did you missed something here?

    The casing of "sum" is not correct either.

    Btw, check this wiki on strategies on manage floating point error, or just use decimal type instead which has higher precision and will not induce floating point errors in your case.

    When use decimal:

    decimal[] arr = new decimal[] { 1.6m, 11.3m, 9.5m, 9.2m, 9m, 8.6m, 5m, 5m, 5m, 4.5m, 4.5m, 3.8m };
    
    var sumResult = arr.Sum(d => d); // 77.0



    Monday, March 18, 2019 4:27 AM
    Answerer

All replies

  • I only see 76.999999999999986 when running your code. Did you missed something here?

    The casing of "sum" is not correct either.

    Btw, check this wiki on strategies on manage floating point error, or just use decimal type instead which has higher precision and will not induce floating point errors in your case.

    When use decimal:

    decimal[] arr = new decimal[] { 1.6m, 11.3m, 9.5m, 9.2m, 9m, 8.6m, 5m, 5m, 5m, 4.5m, 4.5m, 3.8m };
    
    var sumResult = arr.Sum(d => d); // 77.0



    Monday, March 18, 2019 4:27 AM
    Answerer
  • double[] arr = new double[]{14.6,11.3,9.5,9.2,9,8.6,5,5,5,4.5,4.5,3.8}

    var sumResult = arr.sum(d=>d);

    I miss 4 at first elemen

    thank you for your help you save me

    • Edited by Sovannara Monday, March 18, 2019 4:50 AM
    Monday, March 18, 2019 4:48 AM