java - 获取 360 到 1 之间的集合的平均角度方向

标签 java math

我正在尝试获取一组从 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
}

最佳答案

您需要将 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

关于java - 获取 360 到 1 之间的集合的平均角度方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33748607/

相关文章:

c# - 如何实现二元方程的高斯消元法

math - 平面和点之间的有符号距离

java - 如何在Atmosphere框架中配置自定义AtmosphereResource

java - Android 媒体播放器错误 1,-1002

java - Android @RequirePermission 在 onRequestPermissionsResult 中以红色突出显示授予的方法

c - 埃拉托斯特尼筛法,素数 C

java - 使用 Spring Data MongoDB 时,使用 Map 作为 bean 中的属性时出现异常?

java - 如何在Java中获取错误的行号?

sql - PostgreSQL 计算阈值查询

math - 使用 d3.js 绘制 0 到 360 度的圆弧