I'm writing a program to calculate the 'Taylor Series' and I'm getting 'inf' as my output. I'm not done with the program and everything isn't working properly yet, but I want to be able to see my output. Is there a way to shorten the output or make it visible? Thanks for the help.
#include <iostream>
#include <math.h>
using namespace std;
long double taylorSeries(long double input, int degree);
long int factorial(int input);
long double derivative(long double input);
int main(int argc, const char * argv[])
{
long double taylorInput = cos(0);
cout << taylorSeries(taylorInput, 3) << endl;
return 0;
}
// taylor series function
long double taylorSeries(long double input, int degree){
long double i = 0;
long double accumulation = 0;
while (i < degree) {
derivative(input);
accumulation += (pow(input, i))/factorial(i);
i++;
}
return accumulation;
}
// function to calculate factorial
long int factorial(int input){
long int factorial = 0;
if (input == 1) {
factorial = 0;
}
while (input > 0) {
if (factorial == 0) {
factorial = input * (input - 1);
input -= 2;
}
else if (input > 0) {
factorial *= input;
input--;
}
}
return factorial;
}
long double derivative(long double input){
long double derivativeResult = 0;
derivativeResult = (((input + .001) - (input)) / .001);
return derivativeResult;
}
In accumulation += (pow(input, i))/factorial(i);
you are dividing by 0.
On the factorial function you are missing the case for 0, factorial of 0 is 1.
EDIT: Factorial of 1 is also not 0, you should take a look at that factorial function first before going forward.