Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Calculating Sin(x)

1. ## Calculating Sin(x)

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.  Reply With Quote

3. ## Re: Calculating Sin(x)

Welcome to the forum! Please read this topic to learn how to post code in code or highlight tags and other useful info for new members.

Please post your code correctly using code or highlight tags per the above link.  Reply With Quote

#### Tags for this Thread 