C++ Sin function using Taylor


#1

I’m trying to write a function to calculate sin of a number in radiant without using the built in sin function in cmath library. I’ve tried over 10 fixed , can’t seem to find the error.
Thought I’d get some help here.

#include "stdafx.h"
#include <iostream>
#include <cmath>

using namespace std;

int factorial(int n) {
	if (n == 1)
		return 1;
	else
		return n*factorial(n - 1);
}
double sinuss(double x,int n) {

	if (n < 1)
		return x;
	else
		return pow(-1, n)*(pow(x, 2*n + 1) / (factorial(2*n + 1)) + sinuss(x, n - 1));

}

int main()
{
	cout << sinuss(1.0471, 5);
	system("pause");
	 
    return 0;
	
}

Thank You !!


#2

Do you mean that you used a value of 10 for the n parameter of sinuss?

If you look at what you do with n, a value of 10 will result in a call to factorial with n=21

factorial(21) is a pretty large number, it is greater than a 32-bit integer (greater than 64-bit too)


#3

Oh no mate, sorry It was a typo.
I tried changing the code over 10 times , thats what i meant (fixes*) and it’s still not working.
I tried using n=2 , did the calculation on a paper, it works .
But when i run the code it wont work


#4

Nevermind I had a wierd problem with paranthesis ! it’s fixed now ! Thank you.