Trigonometry With Java

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 isa 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); 
See also  How to Create and Deploy QR Codes Online: A Comprehensive Guide

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist