Harjit Singh
Harjit Singh

Reputation: 75

Problem with pow giving me an infinite answer

I'm trying to compute a discount factor given a rate and the number of payments to be made per year.

#include <iostream>
using namespace std;
int main()
{
    uint32_t due_dates_per_year = 2;
    double t = 1;
    double rate = 0.05;
    double df = pow(1 + rate / due_dates_per_year, -due_dates_per_year * t);
    cout << df;
    return 0;
}

The output is "inf" but it should be a little less than 1.

Does anyone know what's going on?

Upvotes: 2

Views: 106

Answers (1)

Bathsheba
Bathsheba

Reputation: 234715

The problem is in the exponent (i.e. the second parameter) of std::pow. The expression

-due_dates_per_year * t

is grouped as (-due_dates_per_year) * t (that's how the C++ grammar parses the expression). The unary negation of the unsigned type produces a large (and also unsigned) number which explains the result.

Other than using a signed type for due_dates_per_year, the rearrangement

double df = std::pow(1 + rate / due_dates_per_year, -t * due_dates_per_year);

is a fix.

Upvotes: 3

Related Questions