Correct cmath pow () in GCC

Code [GCC compiled with -O2 flag]

int main() { vector< vector<int> > matrixa(8); int ff = 5; int s = pow(ff, matrixa.size()); int ss = pow(double(ff), int(matrixa.size())); vector< vector<int> > comb(s); cout << ff << "^" << matrixa.size() << " = " << s << endl; cout << ss << endl; return 0; } 

Output

 5^8 = 390624 390625 

I am wondering why s = 390624 , when should it be 390625 . If I compile code without the -O2 flag, then s = 390625 . Also, casting for ss seems to fix the problem.

What's happening?

My OS is Windows 7 Ultimate x64. Not sure about the GCC version, it comes with the code :: Blocks 10.05.

+4
source share
2 answers

Since floating point arithmetic is not perfect, and when you do

 int s = pow(ff, matrixa.size()); 

The pow result is actually more like 390624.99999 , and when you truncate it to int , it effectively smoothes to 390624. If you expect an integer value there (floating point with a .0 fractional part), you should probably round the pow result.

+6
source

Try assigning a double result and displaying it (with possible larger std::setprecision ) settings. You will see that due to rounding errors the value will be something like 390624.99999999999 (or similar).

The cast to int truncates the fractional part, leaving 390624 . Use std::round to get the desired result.

+5
source

All Articles