Problem calculating series

Hello everyone :)

I'm trying to write a program that calculates sum of a series (x*ln(a))^n/n! (the sum of the series gives a^x.) where n = 0, 1, 2, 3, ... until n reaches a point where (x*ln(a))^n/n! < 0.00001. At that point my program is supposed to stop summing and give the answer - the total sum. a and x are freely chosen, program asks to type those two numbers before calculating the sum.

I choose a=5 and x=3 to check my program.

And here is the weird part. My program seems to calculate the sum and the member of the sequence right until n reaches 13. Then it starts to show wrong values. It's extremely interesting since for n = 0 to 12 it works just fine. The value b is supposed to get smaller and smaller until it reaches 0.00001 but at the point n=13 it starts to get bigger. I don't understand why and I don't know how to make my program calculate the sum for n = 0 to n that when (x*ln(a))^n/n! < 0.00001

My question is what is the problem with my program? :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <cmath>
using namespace std;


int factorial (int a)
{
	int f=1, v;
	for (v=1; v<=a; v++)
	{
		f = f * v;
	}
	return (f);
}


int main ()
{
	float s=0, t = 0.00001, b, x, a;
	signed int n=-1;
	
	cout << "The program counts a^x. Please, type a:\n";
	cin >> a;
	cout << "Type x:\n";
	cin >> x;
	
	do
	{
		n++;
		b = (pow(x*log(a), n))/factorial(n);
		s=s+b;
		cout << "Sum up to this point is " << s << "\n";
		cout << "b = " << b << "\n"; 
		if (b < t)
		{
			cout << "The total sum with the accuracy of 0.00001 is " << s << "\n";
		}
		
	}
	while (b > t);
	

	
	return 0;
}
How large is factorial(13)?
How large value can be stored in int?
Thank you so much!! That was the problem :))
Persimonal - you may need a better way to set up and sum your power series than to work a new term out from scratch each time.

A common approach is to note that each term is a multiple of the previous one. In this case, the nth term is (x log a)/n times the previous one. This update of the added term in the loop would avoid the problem with large factorials that Keskiverto has pointed you to. It is also much more efficient.
Topic archived. No new replies allowed.