Using class Math

Math is yet another class belonging to the core set of the Java programing language. We take a tour on selected methods:

Figure 427. Math.sin(double x) Slide presentation
Code Result Math notation
final double x = 90;
final double y = Math.sin(x);
System.out.println(y + " == sin(" + x + ")");
0.8939966636005579 == sin(90.0) 
y = sin ( x )

exercise No. 134

Common pitfall using trigonometric functions

Q:

We reconsider Figure 427, “Math.sin(double x). Did you expect a value of 0.8939966636005579 corresponding to an angle of 90° here? Discuss the underlying problem.

A:

The mathematically inclined reader may have expected a result of 1.000... corresponding to a right angle of 90° rather than 0.893....

This is a common misconception: At school you were probably using so called degrees ranging from 0° to 360° for describing angle values. In Mathematics however trigonometric functions are being defined as power series e.g.:

sin x = x - x 3 3! + x 5 5! + ... = n = 0 ( -1 ) n x 2n + 1 ( 2n + 1 ) !

As an immediate consequence describing a full circle of angle values the variable x here is ranging from 0 to 2 π rather than from 0° to 360°. This angle unit is called radians. If you still want to use degrees you will have to convert these to radians beforehand by multiplying with 2 π 360° or simply π 180 :

final double x = 90;
final double y = Math.sin(x * Math.PI / 180); //converting degrees to radians
System.out.println(y + " == sin(" + x + ")");