Zld Productions Zld Productions - 2 years ago 106
Java Question

How would I calculate the degree measure of a number like tan(45) in Java?

In case the title was confusing, here is what I mean. When I use the code

to return a number, I can't use
to return 45. I can't just make it simply return 45, because I want it to be dynamic.

How would I return the degree measure of a tangent, sine, or cosine?

Answer Source

That's where functions come in. Say we have the following function:

public double calculateSin(double degrees) {
    return Math.sin(Math.toRadians(degrees));

The function above eliminates the formula altogether, thanks to @LouisWasserman for pointing that out. The below uses the formula.

public double calculateSin(double degrees) {
    return Math.sin(degrees * Math.PI / 180);

This is a function that takes a parameter named degrees and returns the sine of that number in radians. This can be applied to all the other trigonometric functions. Just remember the input must be radians. To convert from degrees to radians, use the formula r = dπ/180 where r is radians and d is degrees. Converting from degrees to radians is this formula: d = 180r/π. Some other examples:

public double calculateTan(double degrees) {
    return Math.tan(degrees * Math.PI / 180);

Again, the above uses the formula for degree conversion to radians. Below is using builtin functions.

public double calculateTan(double degrees) {
    return Math.tan(Math.toRandians(degrees));

You would then call it using calculateTan(180) which then would return 0. All this can then be applied to Math.atan and the other inverse functions.

There is also, of course, a built in functions as shown above for radian & degree conversion, which are Math.toDegrees(double radians) and Math.toRadians(double degrees)

For extra reference, consult the JavaDocs, the Math class is linked here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download