Monday, 3 July 2017

Java code to evaluate the function sin(x)

Problem:

Design an algorithm to evaluate the function sin(x) as defined by the infinite series expansion
sin(x) = x/1! - x3/3! + x5/5! - x7/7!....

Solution:

package com.myprograms;

import java.util.Scanner;


public class SineFunction {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter x value");
double x = s.nextDouble();

        // convert x to an angle between -2 PI and 2 PI
        x = x % (2 * Math.PI);

        // compute the Taylor series approximation
        double term = 1.0;      // ith term = x^i / i!
        double sum  = 0.0;      // sum of first i terms in taylor series

        for (int i = 1; term != 0.0; i++) {
            term *= (x / i);
            if (i % 4 == 1){
            sum += term;
            }
            if (i % 4 == 3){
            sum -= term;
            }
        }
        System.out.println(sum);
s.close();

}

}


Output:
enter x value
90
0.8939966636005563

enter x value
40
0.7451131604793478


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...