簡體   English   中英

獲取 360 度和 1 度之間的集合度數的平均方向

[英]Get average direction of degrees of the set between 360 and 1

我試圖取一組從 0 到 359 的角度並獲得角度的平均方向。 我到處搜索,其中一些示例有效,但由於某種原因,我的代碼無法正常工作。

例如,{355,355,15,15} 組的平均值應該是 5 度,但是我得到了一堆沒有多大意義的不同答案。

我正在使用維基提供的這個方程: https : //en.wikipedia.org/wiki/Mean_of_circular_quantities

public static void main(String[] args) {

    //ATAN2(sum_of_sin(theta), sum_of_cos(theta))

    double[] numbers = {355,355,15,15};
    double sin=0.0, cos=0.0, theta=0.0;

    for(double d : numbers) {
        sin += Math.sin(d);
        cos += Math.cos(d);
    }

    sin = sin / ((double)numbers.length);
    cos = cos / ((double)numbers.length);

    // Using only atan2
    System.out.println("Atan2 Only: " + Math.toDegrees(Math.atan2(sin, cos)));
    // Atan2 Only: 159.71920992022936

    // Using the wiki solution
    if (sin > 0 && cos > 0) {
        theta = Math.atan(sin/cos);
    } else if(cos < 0) {
        theta = Math.atan(sin/cos) + 180;
    } else if(sin < 0 && cos > 0) {
        theta = Math.atan(sin/cos) + 360;
    }
    System.out.println("Wiki Answer: " + theta);
    // Wiki Answer: 179.6460334382022
}

Java 中的數學方法假定您使用弧度而不是度數。 嘗試通過乘以 π / 180 將所有值轉換為弧度,看看是否能解決問題。

您需要將輸入從度數轉換為弧度以將輸入轉換為 sin 和 cos 然后再次返回結果:

    double[] numbers = {355, 5, 15 };
    double sin=0.0, cos=0.0, theta=0.0;

    for(double d : numbers) {
        double s = Math.sin(Math.toRadians(d));
        sin += s;

        double c = Math.cos(Math.toRadians(d));
        cos += c;
    }

    sin = sin / ((double)numbers.length);
    cos = cos / ((double)numbers.length);

    // Using only atan2
    System.out.println("Atan2 Only: " + Math.toDegrees(Math.atan2(sin, cos)));
    // Atan2 Only: 159.71920992022936

    // Using the wiki solution
    if (sin > 0 && cos > 0) {
        theta = Math.atan(sin/cos);
    } else if(cos < 0) {
        theta = Math.atan(sin/cos) + 180;
    } else if(sin < 0 && cos > 0) {
        theta = Math.atan(sin/cos) + 360;
    }
    System.out.println("Wiki Answer: " + theta);
    System.out.println("Wiki Answer in degrees: " + Math.toDegrees(theta));

輸出:

Atan2 Only: 4.9999999999999964
Wiki Answer: 0.08726646259971642
Wiki Answer in degrees: 4.9999999999999964

注意:這種方法存在相當大的缺陷; 將這個答案留在這里,以便其他人了解這些缺陷。 有關詳細信息,請參閱@LutzL 和我(@Nadesri)之間的評論。

也許我遺漏了一些東西......我認為你應該能夠將所有數字相加,取總和模 360(假設度數),然后除以 n

private double avgOfAngles(List<int> numbers) {
    int n = numbers.size();
    int sum = 0;
    for (int i=0; i<numbers; i++) {
        sum += numbers.get(i);
    }
    return (double) (sum % 360) / n;
}

當然,以上假設可接受的答案范圍在 0 到 359 之間,包括 0 到 359; 如果您更喜歡不同的范圍(例如 -180 到 179),則上述解決方案需要適當地抵消。

維基指出 [0, 360] 作為一個可能違反直覺的例子(因為算術平均值是 180,盡管 360 度在大多數情況下與 0 度相同); 我認為上述解決方案至少仍然可以處理這個例子。

暫無
暫無

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

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