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:
Code | Result | Math notation |
---|---|---|
|
0.8939966636005579 == sin(90.0) |
|
No. 137
Common pitfall using trigonometric functions
Q: |
We reconsider Figure 420, “ |
A: |
The mathematically inclined reader may have expected a
result of 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.: As an immediate consequence describing a full circle of angle values the variable x here is ranging from 0 to 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 or simply :
|
No. 138
Using constants from java.lang.Math
.
Q: |
In Exercise Calculating a circle's area avoiding accidental
redefinition you
calculated a given circle's area protecting variables against
accidental redefinition using the
You may have wondered why you had to punch in the value of
such an important constant as
by yourself. Actually Java™ predefines constants in TipYou may want to read the “Static Members” and “Java Packages” sections of [Kurniawan]. |
A: |
The short answer simply is:
In case you bother about using the somewhat clumsy import static java.lang.Math.PI; // Notice the »static« modifier public class CircleAreaCalculator { public static void main(String[] args) { double radius = 2.31; // A circle having a radius (given e.g. in mm). final double area = PI * radius * radius; // This actually refers to Math.PI System.out.println(area); } } We dig a little deeper to fully understand the underlying
concepts. Obtaining a JDK™'s source code and
browsing its implementation package java.lang;
...
public final class Math {
...
/**
* The {@code double} value that is closer than any other to
* <i>pi</i>, the ratio of the circumference of a circle to its
* diameter.
*/
public static final double PI = 3.14159265358979323846;
... This accounts for using the expression The careful reader may have expected an import java.lang.Math; // Optional: Classes from java.lang are imported // implicitely as per the Java language specification. public class CircleAreaCalculator { public static void main(String[] args) { double radius = 2.31; // A circle having a radius (given e.g. in mm). final double area = Math.PI * radius * radius; System.out.println(area); } } But since the |