Conversion Methods


Conversion Methods

The Math and StrictMath classes provide three convenience methods for converting degrees to radians, radians to degrees, and rectangular coordinates to polar coordinates.


   public  static  double  toDegrees(double  angle)
   
   public  static  double  toRadians(double  angle)
   
   public  static  double  atan2(double  y,  double  x)

toDegrees() converts the specified input angle from radians to degrees.

toRadians() converts the specified input angle from degrees to radians.

atan2() converts rectangular coordinates (x, y) to polar coordinates (r, q ). The return value is the q angle, which is calculated by taking the arctangent of the ratio y/x. The value of r can be computed from the expression graphics/16inl02.gif

Example: Converting Angles

The trigonometric functions in the Math and StrictMath classes use angles in units of radians. Most people find it easier to think of angles in terms of degrees. In the ConvertDemo class, the toRadians() method is used to convert a user specified angle in degrees to a radian value that can be used by the sin() and cos() methods.

 import java.io.*; public class ConvertDemo {   public static void main(String args[]) {     double angleDeg, angleRad;     System.out.print("Enter angle in degrees:  ");     //  A BufferedReader reads the user specified     //  angle as a String.  The String is converted     //  into a double value and this value is     //  converted from degrees to radians using the     //  toRadians() method     try {       BufferedReader reader =            new BufferedReader(               new InputStreamReader(System.in));       angleDeg =            Double.parseDouble(reader.readLine());       angleRad = Math.toRadians(angleDeg);       System.out.println("cos("+angleDeg+") = " +                          Math.cos(angleRad));       System.out.println("sin("+angleDeg+") = " +                          Math.sin(angleRad));     } catch (IOException ioe) {}   }    } 

Output ”

The output will vary. If you type in "60" as the input angle the output is ”

 cos(60) = 0.5 sin(60) = 0.86602540378 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net