Wednesday 8 December 2010

Sine Series

The below Java program computes the Sine Series




at a particular x, upto a specified number of terms. The value of x and the summation required upto a particular number of terms can be assigned to the member variables variable and numberOfTerms inside the main() method. It's assumed that the SineSeries.java file is inside the same package where  ExponetialSeries.java is, for we'll be using the Factorial class in it. Here we compute the value of the series at x = 90°, which is π/2 in radian measure.

class SineSeriesSummation {
    static double sineSeriesSummation(double x,byte n)
    {
       double sineSeries = 0;

       for(byte i = 0;i < n;i++)
       {
          if(i % 2 == 0)
          {
             sineSeries += Math.pow(x,2*i + 1) / (double)                                            Factorial.factorial((byte) (2*i + 1));
          }
          else
          {
             sineSeries -= Math.pow(x,2*i + 1) / (double)                                            Factorial.factorial((byte) (2*i + 1));
          }
       }
      return sineSeries;
   }
}


public class SineSeries {

    public static void main(String[] args) {
       final double PI =  3.141592653589793238462643383279502;

       double variable = PI/2;
       byte numberOfTerms = 32;
       System.out.println("The sum of the Sine Series at x = " 

       + variable + " upto the first " + numberOfTerms + " terms is " 
       + SineSeriesSummation.sineSeriesSummation(variable, numberOfTerms));

   }

}
 

The output will be

 
 The sum of the Sine Series at x = 1.5707963267948966 upto the
  first 32 terms is 0.9999966422044658

This is almost the same value which you'll get by using the method sin() in the java.lang.Math class. You can add the below line just below the last in the above code to check that.
 

  System.out.println("Using the sin() method of the java.lang.Math class, 
  the value of the Sine Function at x = " + variable + " is " + Math.sin 
  (variable)); 


Also instead of defining our own value for π as we did above, we can use it from the java.lang.Math class itself as
  
  double variable = Math.PI/2;


The Sine Series generated by wxMaxima

No comments:

Post a Comment