U++ framework
Do not panic. Ask here before giving up.

Home » Community » Coffee corner » Approximate distance calculation
Approximate distance calculation [message #48704] Sat, 26 August 2017 09:55
mirek is currently offline  mirek
Messages: 14290
Registered: November 2005
Ultimate Member
While working on OSD firmware for my FPV plane, I have started playing with the idea how to calculate fast distance approximation:

int ihypot(int x, int y)
{
	if(x < 0)
		x = -x;
	if(y < 0)
		y = -y;
	if(x < y)
		Swap(x, y);
	if(y < (x >> 2) + (x >> 3))
		return x + (y >> 3) + (y >> 5);
	y -= (x >> 2) + (x >> 5);
	return x + (y >> 1) + (y >> 4);
}


This is approximation of sqrt(x*x + y*y).

- if max(x, y) < 168, absolute error < 4 (this has more to do with integer rounding)
- otherwise, the error is less than 2%

Putting it here so that perhaps it can be googled if somebody is looking for something like it...
Previous Topic: Nightly build versioning
Next Topic: Congratulations on "moveable"
Goto Forum:
  


Current Time: Thu Apr 30 18:27:16 GMT+2 2026

Total time taken to generate the page: 0.00412 seconds