簡體   English   中英

在Java中找到角度的余弦

[英]Finding the cos of an angle in java

我被要求根據以下等式找到cos:

我能夠找到角度的罪過,但是當找到cos時,我得到的數字與正確值有很大不同:

我使用以下代碼查找cos。 ps:我不能使用math.cos

余弦表達

public static double cos(double x, int n){

    // declaring cos and factorial

    double cos = 0.0;


    // this loop determines how long does the loop go so the answer is more accurate
    for (long howlong = 1 ; howlong <=n; howlong++){
        double factorial =1;

    // this will calculate the factorial for even numbers ex/ 2*2 = 4 , 4-2 = 2
    // for the denominator 

    for (int factorialnumber=1; factorialnumber<=2*howlong-2; factorialnumber++){
        factorial = factorial * howlong;    

    }

    // now we need to create the pattern for the + and -
    // so we use % that switches the sign everytime i increments by 1

    if (howlong%2==1){
        cos = cos + (double) (Math.pow(x, 2*howlong-2)/factorial);
    }

    else{
        cos = cos - (double) (Math.pow(x, 2*howlong-2)/factorial);
    }
    }
    return cos;
}

編輯:我發現我的錯誤,因為它是乘以乘號而不是乘數的倍數。

您有兩個錯誤。

(錯誤1)您寫在哪里

factorial = factorial * howlong;

應該是

factorial = factorial * factorialnumber;

(錯誤2)在每次通過外循環的迭代中,您都不會重置自己的階乘。 所以你需要移動線

double factorial =1;

向下幾行,使其位於外循環內。

如果您進行了這兩個更改,則cos(Math.PI / 6, 10)0.8660254037844386 ,對我來說似乎是正確的。

您的階乘計算錯誤。 嘗試使用以下代碼:

public static double cos(double x, int n) {

    // declaring cos and factorial

    double cos = 0.0;


    // this loop determines how long does the loop go so the answer is more
    // accurate
    for (long howlong = 1; howlong <= n; howlong++) {

        // now we need to create the pattern for the + and -
        // so we use % that switches the sign everytime i increments by 1

        if (howlong % 2 == 1) {
            cos = cos + Math.pow(x, 2 * howlong - 2) / factorial(2 * howlong - 2);
        }

        else {
            cos = cos - Math.pow(x, 2 * howlong - 2) / factorial(2 * howlong - 2);
        }
    }
    return cos;
}

public static long factorial(long n) {
    long result = 1;
    for (int i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}

您的計算不正確,請更改為

 double value = 1;
            for (int factorialnumber = 1; factorialnumber <= 2 * howlong - 2; factorialnumber++) {
                value = factorialnumber * value;
            }

            factorial = value;
            System.out.println(value + " " + (2 * howlong - 2));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM