Angle Within Range
When following procedures linked to angles, you are sometimes required to ensure the angle falls within a 360 degree range of values.
(Adding multiples of 360 degrees to an angle does not normally affect Trig function results but reduced accuracy is possible when applying Trig Functions to huge angles)The following functions convert out_of_range values into equivilent within_range equivilents.
Private Function Range_360(angle As Double) As Double
' Force angle into the range 0 to 360
angle = angle Mod 360
If angle < 0 Then angle += 360
Return angle
End Function
'
Private Function Range_180(angle As Double) As Double
' Force angle into the range -180 to +180
angle = angle Mod 360
If angle < 0 Then angle += 360
If angle >= 180 Then angle -= 360
Return angle
End Function
'
Private Function Range_2Pi(angle As Double) As Double
' Force angle into the range 0 to (2 * Pi))
angle = angle Mod (2 * Math.PI)
If angle < 0 Then angle += (2 * Math.PI)
Return angle
End Function
'
Private Function Range_Pi(angle As Double) As Double
' Force angle into the range -Pi to + Pi
angle = angle Mod (2 * Math.PI)
If angle < 0 Then angle += (2 * Math.PI)
If angle >= Math.PI Then angle -= 2 * Math.PI
Return angle
End Function
The function below is a "generic" version of the above
suitable for any valid range maximum and range minimum. However,
care should be taken when using it for these reasons
- Angle ranges are normally 0_to_360, -180_to_180, 0_to_2*Pi or -Pi_to+Pi. The above functions handle each of these scenarios. Ranges between other limits are very unusual
- I would normally expect max_x to be exactly 180 degrees (2*Pi radians) more than min_x
- The function will fail or produce unexpected results unless max_x is significantly more than min_x
Private Function Range(x As Double, min_x As Double, max_x As Double) As Double
Dim mmr As Double = max_x - min_x
x = x Mod mmr
If x < min_x Then x += mmr
If x >= max_x Then x -= mmr
Return x
End Function
DigitalDan.co.uk