Calculating Trigonometric Functions

Problem

You need to compute sine, cosine, and other trigonometric functions.

Solution

Use the trig functions in java.lang.Math . Like java.lang.Math.random( ), all the methods of the Math class are static, so no Math instance is necessary. This makes sense, as none of these computations maintains any state. Here is a program that computes a few trigonometric values and displays the values of E and PI that are available in the math library:

// Trig.java 
System.out.println("Java's PI is " + Math.PI); 
System.out.println("Java's e is " + Math.E); 
System.out.println("The cosine of 1.1418 is " + Math.cos(1.1418));

Java 1.3 (Java 2 JDK 1.3) includes a new class, java.lang.StrictMath , which is intended to perform most of the same operations with greater cross-platform repeatability.

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.