moshe-braner / SoftRF

:airplane: Multifunctional, compatible DIY general aviation proximity awareness system
GNU General Public License v3.0
18 stars 4 forks source link

approximate trig functions #7

Closed moshe-braner closed 5 months ago

moshe-braner commented 2 years ago

The ESP32 is fairly slow in floating point math, especially the fancy functions such as sin() or sqrt(). My plans to implement a fancier collision prediction algorithm would significantly increase the use of trig functions. I am not sure if that is a problem or do we have plenty of CPU cycles to spare. Just in case, I've implemented approximation functions that are accurate enough for the purpose, and much faster. Not integer math (which may be hiding in some of the many linked libraries). But simple floating point math. Based on the following two approximations, that are good enough, in restricted ranges of input:

atan(t) (degrees) ~= 45 t + 15.5 (t * (1-t)) -- results within +-0.25 deg for 0<t<1

And for sin(), an approximation that was used by a mathematician named Bhaskara in 7th century India: (Interesting article here: https://scholarworks.umt.edu/cgi/viewcontent.cgi?article=1313&context=tme )

sin(x) ~= 4 x (180 - x) / (40500 - (x * (180 - x))) -- for 0<x<180 degrees.

moshe-braner commented 2 years ago

And now (not yet on github) also added an approximate computation of the hypotenuse, avoiding the square root. Based on: https://www.flipcode.com/archives/Fast_Approximate_Distance_Functions.shtml - with one added "iteration". Maximum error less than 0.1%. Essentially, if x is the larger of the sides x & y: h = ( x 0.9834 ) + ( y 0.4307 ); return (0.5 ((xx + y*y) / h + h));