KnowledgeBoat Logo

Computer Applications

Write a program that computes sin x and cos x by using the following power series:

sin x = x - x3/3! + x5/5! - x7/7! + ……

cos x = 1 - x2/2! + x4/4! - x6/6! + ……

Java

Java Nested for Loops

6 Likes

Answer

import java.util.Scanner;

public class KboatSeries
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter x: ");
        int x = in.nextInt();
        
        double sinx = 0, cosx = 0;
        int a = 1;
        
        for (int i = 1; i <= 20; i += 2) {
            long f = 1;
            for (int j = 1; j <= i; j++) 
                f *= j;
            
            double t = Math.pow(x, i) / f * a;
            sinx += t;
            a *= -1;
        }
        
        a = 1;
        for (int i = 0; i <= 20; i += 2) {
            long f = 1;
            for (int j = 1; j <= i; j++) 
                f *= j;
            
            double t = Math.pow(x, i) / f * a;
            cosx += t;
            a *= -1;
        }
        
        System.out.println("Sin x = " + sinx);
        System.out.println("Cos x = " + cosx);
    }
}

Output

BlueJ output of Write a program that computes sin x and cos x by using the following power series: sin x = x - x 3 /3! + x 5 /5! - x 7 /7! + …… cos x = 1 - x 2 /2! + x 4 /4! - x 6 /6! + ……

Answered By

2 Likes


Related Questions