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 或其他東西)附加到此任務,您將獲得一個動畫時鐘。
更多閱讀: |
---|
GO TO FULL VERSION