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?
Your problem comes from the
-(m-period+1)part of your call topow.periodis declared asso when
gets evaluated you have
so you get
360as anunsigned intand when you negate it, it wraps around and becomes a very large number (4294966936for a 32 bitint). That means you are doingnot
You need to make
periodanintto get the correct results.If you have a number that must not be negative, don't use an unsigned type. Nothing about
unsignedstops 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.