1. Introduction
1.介绍
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.
在这个简短的教程中,我们将看看如何使用Java的Math.sin()函数来计算正弦值,以及如何在度数和弧度之间转换角度值。
2. Radians vs. Degrees
2.弧度与度数
By default, the Java Math library expects values to its trigonometric functions to be in radians.
默认情况下,JavaMath库希望其三角函数的值以弧度为单位。
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:
Java通过toRadians和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.
每当我们使用Java的任何三角函数时,我们应该首先考虑输入的单位是什么。
3. Using Math.sin
3.使用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:
我们可以通过看一下Math.sin方法来了解这一原则的作用,这是Java提供的众多方法之一。
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.
由于thirtyDegreesInRadians已经是弧度单位,我们不需要首先转换它来获得相同的结果。
4. Conclusion
4.结论
In this quick article, we’ve reviewed radians and degrees and then saw an example of how to work with them using Math.sin.
在这篇快速文章中,我们回顾了弧度和度,然后看到了一个如何使用Math.sin.来处理它们的例子。
As always, check out the source code for this example over on GitHub.
一如既往,请在GitHub上查看这个例子的源代码,。