0

I have a simple program that calculates the sum of a vector. Here is the implementation.

double sum(vector<double> v) {
  double sum = 0;
  for (size_t i = 0; i < v.size(); i++) {
    sum += v[i];
  }
  return sum;
}

But when I test with decimal numbers, it doesn't seem to work.

void test_sum_decimal() {
  cout << "test_sum_decimal" << endl;

  vector<double> test = {1.2, 3, 6.5, 0.1};
  cout << sum(test) << endl; // Prints 10.8
  if (sum(test) == 10.8) {
    cout << "EQUAL" << endl; // Doesn't print "EQUAL"
  }
  assert(sum(test) == 10.8); // Terminates program because expression is false

  cout << "PASS!" << endl;
}

I have a feeling it is due to the datatype double not being 100% precise, but I do not know for sure.

Any help is appreciated. Thank you :)

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
ohjuny
  • 481
  • 2
  • 5
  • 20
  • Most values like 1.1 10.8 are not representable in IEEE floating point binary so you get something with a tiny variation. Numbers like 1.5 3.75 2.125 are perfectly representable and operations with them will produce exact results. This is talked about all the time here and I'm sure it will be tagged to one of those. – doug Sep 11 '18 at 03:04
  • 1
    btw `10.8f == 10.8f` never evaluates to false – Alexey Andronov Sep 11 '18 at 03:35
  • 1
    duplicates: ["i < 0.7" is true following an "float i = 0.7" initialization above?](https://stackoverflow.com/q/13590519/995714), [0.7 is not less than 0.7 but wrong result gets printed](https://stackoverflow.com/q/25458046/995714), [floating point values comparison failure](https://stackoverflow.com/q/17475977/995714), [In this statement if() return true. How possible it? float a=0.7; if(a<0.7)](https://stackoverflow.com/q/52243425/995714) – phuclv Sep 11 '18 at 05:35

0 Answers0