This is the Java Program to Implement the cos() Function (approximately).

Given an angle say x, in degrees find out the cosine of the angle approximately.

The cosine of an angle x can be calculated using the following equation

**cos x = 1 – (x ^{2})/2! + (x^{4})/4! – (x^{6})/6! + ….. = Summation ((-1)^{n} * x^{(2n)}/(2n)!) for n = 0 to n = infinity.**

Note: In the series, x is in radians.

Here is the source code of the Java Program to Implement the cos() Function(approximately). The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

`// Java Program to Implement the cos() Function(approximately)`

import java.io.BufferedReader;

import java.io.InputStreamReader;

public class Cosine {

`// Function to read user input and calculate the cosine of the angle`

public static void main(String[] args) {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

double x;

try {

System.out.println("Enter the angle whose cosine is to be

calculated in degrees");

x = Double.parseDouble(br.readLine());

} catch (Exception e) {

System.out.println("An error occurred");

return;

`}`

double y;

y = x*Math.PI/180;

int n = 10;

int i,j,fac;

double cosine = 0;

for(i=0; i<=n; i++){

fac = 1;

for(j=2; j<=2*i; j++){

fac*=j;

`}`

cosine+=Math.pow(-1.0,i)*Math.pow(y,2*i)/fac;

`}`

System.out.format("The cosine of " + x + " is %f",cosine);

`}`

`}`

1. In function main(), firstly the angle is entered in degrees and it is converted into radians.

2. The loop for(i=0; i<=n; i++) is used to calculate the ith term of the series.

3. The nested loop for(j=2; j<=2*i; j++) is used to calculate the factorial of 2i.

4. Finally, the ith term is added to the variable cosine.

**Time Complexity: O(1)**.

Case 1 (Simple Test Case): Enter the angle whose cosine is to be calculated in degrees 45 The cosine of 45.0 is 0.707107 Case 2 (Simple Test Case - another example): Enter the angle whose cosine is to be calculated in degrees 75 The cosine of 75.0 is 0.258819

**Sanfoundry Global Education & Learning Series – Java Programs.**

**If you find any mistake above, kindly email to [email protected]**

**Related Posts:**

- Apply for Java Internship
- Practice Information Technology MCQs
- Practice BCA MCQs
- Apply for Computer Science Internship
- Practice Programming MCQs