Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Using Math.sin with Degrees

$
0
0

1. Introduction

In this short tutorial, we’ll look at how to calculate sine values using Java’s Math.sin() function and how to convert angle values between degrees and radians.

2. Radians vs. Degrees

By default, the Java Math library expects values to its trigonometric functions to be in radians.

As a reminder, radians are just another way to express the measure of an angle, and the conversion is:

double inRadians = inDegrees * PI / 180;
inDegrees = inRadians * 180 / PI;

Java makes this easy with toRadians and toDegrees:

double inRadians = Math.toRadians(inDegrees);
double inDegrees = Math.toDegrees(inRadians);

Whenever we are using any of Java’s trigonometric functions, we should first think about what is the unit of our input.

3. Using Math.sin

We can see this principle in action by taking a look at the Math.sin method, one of the many that Java provides:

public static double sin(double a)

It’s equivalent to the mathematical sine function and it expects its input to be in radians. So, let’s say that we have an angle we know to be in degrees:

double inDegrees = 30;

We first need to convert it to radians:

double inRadians = Math.toRadians(inDegrees);

And then we can calculate the sine value:

double sine = Math.sin(inRadians);

But, if we know it to already be in radians, then we don’t need to do the conversion:

@Test
public void givenAnAngleInDegrees_whenUsingToRadians_thenResultIsInRadians() {
    double angleInDegrees = 30;
    double sinForDegrees = Math.sin(Math.toRadians(angleInDegrees)); // 0.5

    double thirtyDegreesInRadians = 1/6 * Math.PI;
    double sinForRadians = Math.sin(thirtyDegreesInRadians); // 0.5

    assertTrue(sinForDegrees == sinForRadians);
}

Since thirtyDegreesInRadians was already in radians, we didn’t need to first convert it to get the same result.

4. Conclusion

In this quick article, we’ve reviewed radians and degrees and then saw an example of how to work with them using Math.sin.

As always, check out the source code for this example over on GitHub.


Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>