Reputation: 400
My general task is to compute According to Wolfram,
I expected the following to return the same:
#include <iostream>
#include <vector>
#include <math.h>
unsigned long long f(const std::vector<unsigned> &coefficients)
{
unsigned short exponent = coefficients.size() - 1;
unsigned long long sum;
for (unsigned i : coefficients)
{
sum += i * pow(36, exponent);
--exponent;
}
return sum;
}
int main()
{
std::cout << f({9,13,19,6,7,8,2});
}
but instead it returns 20416905041
.
The minimum capacity of an unsigned long long integer is 0 to 18446744073709551615, according to Alex B on this question, so capacity doesn't appear to be the problem.
g++ mwe.cpp -std=c++11 -omwe
Upvotes: 1
Views: 132
Reputation: 400
From M.M's comment on the question:
pow
is a floating point function and therefore will be susceptible to rounding errors. You should use integer variables (do repeated multiplication by 36) instead.
Upvotes: 1