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