trouble with calculations

Ok, I'm having some issues with miscalculation here and i cannot figure it out?

example:

when i do

long numberTest = 14*13*12*11*10*9*8*7*6*5*4*3*2*1;
cout << numberTest;
cin.get();

it outputs a calculation completely different from my calculator and PC calculator.

when i do anything less the 12 or so it computes and outputs fine

long numberTest = 10*9*8*7*6*5*4*3*2*1;
cout << numberTest;
cin.get();

what its going on here?
some sort of coercion converting it to the incorrect number?
wrong data type? I'm a bit lost.

Any help would be greatly appreciated
Overflow. The number of bytes used to represent the number is fixed
(sizeof(long) will give you the number of bytes, numeric_limits<long>::max() the max number that can be stored)

You will need to use a bignum library for such computation (or change the data type to double if you don't care about precision).
Ok, here's what i'm trying to do...

Compare the value of 14! to the value produced by solving Stirlings Approximation formula:

n approximately equal to e^-14 * n^n * sqrt(2(PI)n)

I understand that the value of 14! exceeds the data type I used. But it seems no matter which data type I use i cannot generate the proper result
using this formula:

14*13*12*11*10*9*8*7*6*5*4*3*2*1

I can however generate the correct answer usings stirlings formula...

Heres my code so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream> 
#include <string> 
#include <iomanip> 
#include <cmath> 

using namespace std;

int main() 
{
const double PI = 3.14159265;
double stirlingsFormula =  (1 / (pow(2.71828, 14.00))) * (pow(14.00, 14.00)) * (sqrt(2*PI*14.00));
double stirlingsFormulaExp = (exp(-14.00)) * (pow(14.00, 14.00)) * (sqrt(2*PI*14.00)); // just using exponential function here to simplify code later on
long exactFact = 14*13*12*11*10*9*8*7*6*5*4*3*2*1;
cout << stirlingsFormula << endl;
cout << stirlingsFormulaExp << endl;
cout << float(exactFact) << endl;
cout << exactFact;
cin.get();
}

as you see the two are very different. I can work out the correct answer with paper and pencil and on a calculator.. but something i just cannot seem to figure out how to store 14! properly, which data type to use to display it either as a decimal value, integer or in scientific notation! 




Last edited on
when i change exactFact to a double the result is incorrect.
This:

double exactFact = 14*13*12*11*10*9*8*7*6*5*4*3*2*1;

would still be wrong because the calculation is still an integer calculation (which will still overflow) before being converted to double.

You need to do the calulation as double from the start - you need to change at least one of
the numbers to be double for this to happen.

Here we will change the 14 to a double.
double exactFact = 14.0*13*12*11*10*9*8*7*6*5*4*3*2*1;
Topic archived. No new replies allowed.