This is the Java Program to Implement the sin() Function (approximately).
Given an angle say x, in degrees find out the sine of the angle approximately.
The sine of an angle x can be calculated using the following equation
sin x = x – (x3)/3! + (x5)/5! – (x7)/7! + ….. = Summation ((-1)n* x(2n+1)/(2n+1)!) 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 Sine {
// Function to calculate and display sine of an 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 sine 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 sine = 0;
for(i=0; i<=n; i++){
fac = 1;
for(j=2; j<=2*i+1; j++){
fac*=j;
}
sine+=Math.pow(-1.0,i)*Math.pow(y,2*i+1)/fac;
}
System.out.format("The sine of " + x + " is %f",sine);
}
}
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+1; j++) is used to calculate the factorial of 2i+1.
4. Finally, the ith term is added to the variable sine.
Time Complexity: O(1).
Case 1 (Simple Test Case): Enter the angle whose sine is to be calculated in degrees 30 The sine of 30.0 is 0.500000 Case 2 (Simple Test Case - another example): Enter the angle whose sine is to be calculated in degrees 60 The sine of 60.0 is 0.866025
Sanfoundry Global Education & Learning Series – Java Programs.
- Practice BCA MCQs
- Apply for Computer Science Internship
- Apply for Java Internship
- Check Programming Books
- Practice Programming MCQs