O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required