Algorithm Request: Comparison against a range that wraps


Author Message
vegipete

Guru

Joined: 29/01/2013
Location: Canada
Posts: 1182
Posted: 11:44pm 24 Jun 2021      

Here's an example with degrees:

'target_angle' is where you want to be.
'current_angle' is where you are.
'tolerance' is whether you are close enough.
All angles are in degrees MOD 360, ie from 0 to 359.99whatever
angle_min = target_angle - tolerance
angle_max = target_angle + tolerance
if (angle_min < current_angle) AND (current_angle < target_max) then DoSomething
This won't work with wrapping.

Instead
angle_min = target_angle - tolerance
angle_max = target_angle + tolerance
if angle_min < 0 then
  if current_angle > angle_min+360 OR current_angle < angle_max then DoSomething
elseif angle_max >= 360 then
  if current_angle > angle_min OR current_angle < angle_max-360 then DoSomething
elseif angle_min < current_angle AND current_angle < angle_max then
  DoSomething
endif
works, but seems so convoluted and crazy. But maybe that's what is required.