write a java program for sinx series for n= 20
Answers
Sine Series in Java
The sine function can be written with the help of Taylor Series. The Taylor Series for sine is:
We need the summation upto 20 terms. So we will set up a loop to run 20 times. We will take user input for the value of x. This value is in radians.
Here's a Java Program:
import java.util.Scanner; //Importing Scanner
public class Brainly //Creating class
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //Creating Scanner object
System.out.print("Enter the value of x: ");
double x = sc.nextDouble(); //User input for x
int n=20;
double Sum = 0; //Creating and Initialising Sum to 0
for(int i=0;i<n;i++) //Setting a loop
{
Sum += (Math.pow(-1,i)*Math.pow(x,2*i+1))/factorial(2*i+1); //Adding the terms
}
System.out.println("sin(x) = "+Sum); //Printing Sum
}
static double factorial(int n) //Function to find factorial
{
double fact=1;
for(int i=2;i<=n;i++)
{
fact = fact*i; //Each integer till n is multiplied
}
return fact; //Returning the factorial
}
}