CodeGym /Java 博客 /随机的 /Java 中的 Math.cos() 方法
John Squirrels
第 41 级
San Francisco

Java 中的 Math.cos() 方法

已在 随机的 群组中发布
Java 中的Math类包含很多数学函数。三角函数是最重要的编程函数之一。其中一个函数是Math.cos()

用于编程的三角函数?

当然,有些程序员在他们的工作中几乎从未遇到过三角函数,但尽管如此,对于许多任务来说,这些函数是极其重要的。例如,对于计算机图形或游戏逻辑。特别是,正弦和余弦涉及所谓的旋转矩阵,您可以使用它来旋转对象和世界。如果你需要计算沿地图的路径长度,三角函数可以派上用场。

Java 中的 Math.cos() 方法

Math类的double cos (double x)方法返回x的余弦值,其中x是一个参数,以弧度为单位的角度。这是Java.lang.Math.cos()方法的声明:

double cos(double x)
如果您对以弧度计算角度感到不自在,可以使用特殊函数将弧度转换为度数:

double toDegrees(double angRad)
还有一个反函数可以将度数转换为弧度,这也很有用。

double toRadians(double angDeg)
这是java.lang.Math.cos() 的代码示例:

public class CosExample {
   public static void main(String[] args) {
       
       int x1 = 1;
       double x2 = 0.5;
       double x3 = Math.PI;

       //using java.lang.Math.cos() for 1, 0.5 and PI rad 

       System.out.println("cosine of " + x1 + " rads = " + Math.cos(x1));
       System.out.println("cosine of  " + x2 + " rads = " + Math.cos(0));
       System.out.println("cosine  " + x3 + " rads = " + Math.exp(x3));


       //here we declare an 60 degrees angle

       double degree = 60;
       //here we use Math.toRadians to convert 60 degrees to radians, use the cos() method
       //to calculate the cosine of 60 degrees angle and print the result out
       System.out.println("cosine of " + degree + " degrees = " + Math.cos(Math.toRadians(degree)));

   }
}
输出是:
1 弧度的余弦 = 0.5403023058681398 0.5 弧度的余弦 = 1.0 余弦 3.141592653589793 弧度 = 23.140692632779267 60.0 度的余弦 = 0.5000000000000001

一些特殊情况

在数学中有不确定形式、正无穷大和负无穷大的概念。一个数除以 0.0 给出无穷大,正数或负数取决于该数的正负性。您可以通过不同的方式获得不确定的形式。例如,如果您尝试将零除以零或将无穷大除以无穷大。在 Java 中, Double类中有一些特殊的常量,例如 Double.NaN(不是数字,你可以说它是一种不确定的形式)、Double.POSITIVE_INFINITY 和 Double.NEGATIVE_INFINITY。Math.cos()方法在面对这三个概念时会以特定的方式表现。如果参数为 NaN 或无穷大,则Math.cos()为 NaN。让我们看一个代码示例:

public class CosSpecialCases {

       public static void main(String[] args) {

           double positiveInfinity = Double.POSITIVE_INFINITY;
           double negativeInfinity = Double.NEGATIVE_INFINITY;
           double nan = Double.NaN;

           //The argument is positive infinity, the output is NaN
           System.out.println(Math.cos(positiveInfinity));

           //The argument is negative infinity, the output NaN
           System.out.println(Math.cos(negativeInfinity));

           //The argument is NaN, the output is NaN
           System.out.println(Math.cos(nan));
       }
   }
输出是:
南南南

适合初学者的正弦和余弦任务

尝试使用Math.cos()Math.sin()对时钟指针的运动进行编程。您还可以将图形(使用 Processing、JavaFX 或其他东西)附加到此任务,您将获得一个动画时钟。

更多阅读:

评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION