Search code examples
c++c++11stdcmath

C++ function std::pow() returns inf instead of a value


I've got a problem with returned value by std::pow(). Basically, I have following line in the code:

#include <cmath>
int main()
{
     double rate = 1.0033333333333334;
     int m = 360;
     unsigned int period = 1;
     double res = std::pow(rate, -(m-period+1));
}

And res has a value of inf. However, when I paste std::pow(rate, -(m-period+1)) to Visual Studio watch while debugging it has a proper value of 0.30179586515268314. Does anyone know what's the source of this discrepancy?

See http://coliru.stacked-crooked.com/a/ec78c5172cf53e03


Solution

  • Your problem comes from the -(m-period+1) part of your call to pow. period is declared as

    unsigned int period = 1;
    

    so when

    -(m-period+1)
    

    gets evaluated you have

       -(int - unsigned int + int)
    == -(unsigned int)
    

    so you get 360 as an unsigned int and when you negate it, it wraps around and becomes a very large number (4294966936 for a 32 bit int). That means you are doing

    1.0033333333333334 ^ 4294966936
    

    not

    1.0033333333333334 ^ -360
    

    You need to make period an int to get the correct results.


    If you have a number that must not be negative, don't use an unsigned type. Nothing about unsigned stops negative numbers, it just turns them into a positive number. If you want to make sure a number isn't negative, use a signed type and an if statement.