简体   繁体   中英

Calculating accuracy of rotation

So I have a variable containing rotation in degrees, and I have an ideal rotation, and what I want is the percentage of accuracy within 20 degrees in either direction.

var actualRotation = 215
var idealRotation = 225

var accuracy = magicFunction(actualRotation, idealRotation)

In this case, the actualRotation is 10 degrees off from idealRotation , so with a 20 degree threshold in either direction, that's a 50% accuracy. So the value of accuracy would be 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

How can I achieve this?

Try this (just run code snippet):

 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));

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);
 }

The previous answers were good, but they don't handle the case where the difference crosses the zero-singularity.

Eg when the angles are 5 and 355 , you expect a difference of 10, but a simple subtraction gives 350. To rectify this, subtract the angle from 360 if it is bigger than 180.

For the above to work, you also need the angles to be in the range [0, 360) . However this is a simple modulo calculation, as below.

Code:

 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)


EDIT: a graphical illustration of why the previous method would be insufficient:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM