I'm trying to calculate sin(x) without using Math.sin(x). The formula for sin(x) is: x - x^3/3! + x^5/5! ...
I can't seem to get the coding for the alternating +/- right. Here's my program:
import java.util.Scanner;
import java.lang.Math;
class Sin
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int n, c, fact = 1, count = 1;
double x, sum = 0, sum_sin = 0, result;
System.out.println("Enter positive odd integer");
n = kb.nextInt();
System.out.println("Enter x");
x = kb.nextDouble();
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
while (count <= n)
{
result = Math.pow(x,count);
sum = result/fact;
count++;
if (count % 2==0)
{
x = -x;
count++;
}
sum_sin = sum_sin + sum;
}
System.out.println(sum_sin);
System.out.println(Math.sin(x));
}
}
It would be greatly appreciated if somebody could help me.