Trigonometric functions

From Rosetta Code
Revision as of 20:37, 5 January 2008 by rosettacode>Mwn3d (Created page with Java example.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Trigonometric functions
You are encouraged to solve this task according to the task description, using any language you may know.

If your language has a library or built-in functions for trigonometry, show examples of sine, cosine, tangent, and their inverses using the same angle in radians and degrees. If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.

Java

Java's Math class contains all six functions and is automatically included as part of the language. The functions all accept radians only, so conversion is necessary when dealing with degrees. The Math class also has a PI constant for easy conversion.

public class Trig {
	public static void main(String[] args) {
		//Pi / 4 is 45 degrees. All answers should be the same.
		double radians = Math.PI / 4;
		double degrees = 45.0;
		//sine
		System.out.println(Math.sin(radians) + " " + Math.sin(degrees * Math.PI / 180));
		//cosine
		System.out.println(Math.cos(radians) + " " + Math.cos(degrees * Math.PI / 180));
		//tangent
		System.out.println(Math.tan(radians) + " " + Math.tan(degrees * Math.PI / 180));
		//arcsine
		System.out.println(Math.asin(radians) + " " + Math.asin(degrees * Math.PI / 180));
		//arccosine
		System.out.println(Math.acos(radians) + " " + Math.acos(degrees * Math.PI / 180));
		//arctangent
		System.out.println(Math.atan(radians) + " " + Math.atan(degrees * Math.PI / 180));
	}
}