Question: 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?

Answer: 
Try this (just run code snippet):

```js
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));
```
The previous answers were good, but they don't handle the case where the difference crosses the zero-singularity.

E.g. 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:

```js
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:

[![enter image description here](https://i.stack.imgur.com/5h80o.png)](https://i.stack.imgur.com/5h80o.png)