Last active
April 5, 2017 15:08
-
-
Save izackp/7e99893410967411fe10 to your computer and use it in GitHub Desktop.
Hypothenuse Calculations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
h = sqrt(a² + b²); | |
//All these assume 0 ≤ a ≤ b. | |
h = ((sqrt(2) - 1) * a) + b; //Max Error: 8.24% over true value, b must the be larger number | |
h = 0.414213562 * a + b; //Same as above. Either works compiler will optimize. | |
h = 4142 * a / 10000 + b; //Same as above. We just only use ints | |
h = (a >> 1) + b; //Max Error: a/2 //Simplified version of above to be faster and less accurate | |
h = b + 0.337 * a // max error ≈ 5.5 % | |
h = max(b, 0.918 * (b + (a>>1))) // max error ≈ 2.6 % | |
h = b + 0.428 * a * a / b // max error ≈ 1.04 % | |
//Taken From: http://www.flipcode.com/archives/Fast_Approximate_Distance_Functions.shtml | |
u32 approx_distance( s32 dx, s32 dy ) | |
{ | |
u32 min, max, approx; | |
if ( dx < 0 ) dx = -dx; | |
if ( dy < 0 ) dy = -dy; | |
if ( dx < dy ) | |
{ | |
min = dx; | |
max = dy; | |
} else { | |
min = dy; | |
max = dx; | |
} | |
// coefficients equivalent to ( 123/128 * max ) and ( 51/128 * min ) | |
// Uncomment if you don't want to use '*' | |
//return ((( max << 8 ) + ( max << 3 ) - ( max << 4 ) - ( max << 1 ) + ( min << 7 ) - ( min << 5 ) + ( min << 3 ) - ( min << 1 )) >> 8 ); | |
approx = ( max * 1007 ) + ( min * 441 ); | |
if ( max < ( min << 4 )) | |
approx -= ( max * 40 ); | |
// add 512 for proper rounding | |
return (( approx + 512 ) >> 10 ); | |
} | |
/* Iterations Accuracy | |
* 2 6.5 digits | |
* 3 20 digits | |
* 4 62 digits | |
* assuming a numeric type able to maintain that degree of accuracy in | |
* the individual operations. | |
*/ | |
#define ITER 3 | |
double dist(double P, double Q) { | |
/* A reasonably robust method of calculating `sqrt(P*P + Q*Q)' | |
* | |
* Transliterated from _More Programming Pearls, Confessions of a Coder_ | |
* by Jon Bentley, pg. 156. | |
*/ | |
double R; | |
int i; | |
P = fabs(P); | |
Q = fabs(Q); | |
if (P<Q) { | |
R = P; | |
P = Q; | |
Q = R; | |
} | |
/* The book has this as: | |
* if P = 0.0 return Q; # in AWK | |
* However, this makes no sense to me - we've just insured that P>=Q, so | |
* P==0 only if Q==0; OTOH, if Q==0, then distance == P... | |
*/ | |
if ( Q == 0.0 ) | |
return P; | |
for (i=0;i<ITER;i++) { | |
R = Q / P; | |
R = R * R; | |
R = R / (4.0 + R); | |
P = P + 2.0 * R * P; | |
Q = Q * R; | |
} | |
return P; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment