Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Jan 12, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Trigonometry With Java

The java.lang.Math package has useful trigonometric functions such as:
public static native double sin(double a) 

public static native double asin(double a).

So, if we write code:
double x = 90; 
double y = Math.sin(x); 

We expect y to be 1.0, right? Unfortunately this is not true. In fact, we should be aware of a few points in order to successfully use trigonometric facilities of java.lang.Math package.

1. Trigonometric functions of the Math package work in radians, not degrees. pi radians=360 degrees. So, if we want to obtain the value if sin of 90 degrees, we can write:

//conversion from degree to radian 
static final double degToRad = Math.PI/180; 
double x = 90*degToRad; 
double y = Math.sin(x); 
Now, y has a value of 1.0. 
Similarly, if we wan to obtain the asin of 1, 
you would write 
double z=Math.asin(1); 
but z will contain a value is radian 
so , we'll do 
z *= 180; 

This will give you 90 in degrees. 2. We need write Math.sin instead of plain sin because sin, cos, tan, etc. are static functions. Java is picky and verbose. It wants the "Math.", even when there is no name clash with a sin function in some class other than Math, or some package other than java.lang. In this way, Java prevents the possibility of an eventual name clash by requiring fully qualified names for static functions like Math.sin. In fact, we should precede all static function and method invocations with the class name.

3. We need the Math.PI instead of plain PI because PI is a static constant. JDK 1.2 has added two convenience methods for degree to radian and radian to degree conversions:

public static double toDegrees(double angrad); 
public static double toRadians(double angdeg); 
Behrouz Fallahi
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date