计算轮换的准确性

时间:2017-09-28 13:10:40

标签: javascript math pseudocode

所以我有一个包含旋转度数的变量,我有一个理想的旋转,我想要的是在任一方向上20度内的精度百分比。

var actualRotation = 215
var idealRotation = 225

var accuracy = magicFunction(actualRotation, idealRotation)

在这种情况下,actualRotationidealRotation相差10度,因此在任一方向上都有20度的阈值,即50%的准确度。因此accuracy的值为0.5

var accuracy = magicFunction(225, 225)  // 1.0
var accuracy = magicFunction(225, 210)  // 0.25
var accuracy = magicFunction(245, 225)  // 0.0
var accuracy = magicFunction(90, 225)   // 0.0

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:1)

试试这个(只运行代码段):

function magicFunction(actualRotation , idealRotation ) {
    var diff = Math.abs(actualRotation - idealRotation);
    var accurrancy = 1 - (diff / 20);
    accurrancy = accurrancy < 0 ? 0 : accurrancy;
    return accurrancy;
}
console.log("225, 225: ", magicFunction(225, 225)); 
console.log("225, 210: ", magicFunction(225, 210));
console.log("245, 225: ", magicFunction(245, 225));
console.log("90, 225: ", magicFunction(90, 225));

答案 1 :(得分:1)

var actualRotation = 215
var idealRotation = 225
var diff = abs(actualRotation - idealRotation);
if (diff > 20) 
   console.log(0);
else{
   accuracy = 1 - (diff/ 20);
   console.log(accuracy);
 }

答案 2 :(得分:0)

之前的答案很好,但他们没有处理差异超过零奇点的情况。

E.g。当角度 5 355 时,您预计会有10的差异,但是简单的减法会给出350.要纠正此情况,如果角度大于360,则从360减去角度180。

要使上述工作正常,您还需要角度在 [0,360)范围内。然而,这是一个简单的模数计算,如下所示。

代码:

function normalize(angle) {
   if (angle < 0)
      return angle - Math.round((angle - 360) / 360) * 360;
   else if (angle >= 360)
      return angle - Math.round(angle / 360) * 360;
   else
      return angle;
}

function difference(angle1, angle2) {
   var diff = Math.abs(normalize(angle1) - normalize(angle2));
   return diff > 180 ? 360 - diff : diff;
}

function magicFunction(actualRotation, idealRotation, limit) {
   var diff = difference(actualRotation, idealRotation);
   return diff < limit ? 1.0 - (diff / limit) : 0.0;
}

// tests
console.log(difference(10, 255)); // 115 (instead of the incorrect answer 245)
console.log(magicFunction(5, 355, 20)); // 0.5 (instead of 0 as would be returned originally)

编辑:前一种方法不足的原因的图解说明:

enter image description here