/* Improved v2Len function */ #include "vector2.h" /* For the vector structure declaration */ #include /* For sqrt, sin, cos & atan2 functions */ #include float v2Len(vector2 v) { /* Length of vector */ float a = fabs(v.x), b = fabs(v.y), c; /* absolute values */ if (b > a) { /* wrong one larger ? */ c = b; b = a; a = c; /* exchange */ } /* Now a is larger */ if (a == 0.0) { return a; /* Both components are zero */ } b /= a; /* compute b/a */ if (b < FLT_EPSILON) { return a; /* Answer very close to a */ } return a * sqrt(1.0 + b*b); /* full Pythagoras' rule */ } /********* test main *********/ #include main () { vector2 a = {0.7*FLT_MAX, 0.7*FLT_MAX}, b = {1, FLT_EPSILON*0.1}, c = {FLT_MIN, FLT_MIN}; float d, e, f; d = v2Len(a); e = v2Len(b); f = v2Len(c); printf("v2Len(a) = %g - should be a bit below %g\n", d, FLT_MAX); printf("v2Len(b) = %g - should be 1\n", e); printf("v2Len(c) = %g - should be about %g\n", f, FLT_MIN*1.414); return 0; }