Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero inner product when using std::inner_product

The C++ program below should return a stricly positive value. However, it returns 0.

What happens ? I suspect an int-double conversion, but I can't figure out why and how.

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main()
{

    vector<double> coordinates;
    coordinates.push_back(0.5);
    coordinates.push_back(0.5);
    coordinates.push_back(0.5);

     cout<<inner_product(coordinates.begin(), coordinates.end(), coordinates.begin(), 0)<<endl;

    return 0;
}
like image 908
Klaus Avatar asked Aug 22 '12 00:08

Klaus


1 Answers

This is because you provided zero as an integer constant. The resultant operations are all in integers, so the final value (0.75) is truncated to an int as well.

Change zero to 0.0 to make it work:

cout << inner_product(coord.begin(), coord.end(),coord.begin(), 0.0) << endl;

This produces 0.75 on ideone.

like image 85
Sergey Kalinichenko Avatar answered Oct 12 '22 00:10

Sergey Kalinichenko