math.inc
math.inc
CPP1new _a = 1103515245;2new _c = 12345;3new _m = 2147483647;45// Fixed point accuracy6const FP = 8;7const PI_FIXED = 804;8const PI_2_FIXED = PI_FIXED >> 1;9const PI_4_FIXED = PI_FIXED >> 2;10const RAD_2_DEG = (180 << FP) / PI_FIXED;1112new sin8LUT[] = [13 0, 4, 8,14 13, 17, 22,15 26, 31, 35,16 40, 44, 48,17 53, 57, 61,18 66, 70, 74,19 79, 83, 87,20 91, 95, 100,21 104, 108, 112,22 116, 120, 124,23 128, 131, 135,24 139, 143, 146,25 150, 154, 157,26 161, 164, 167,27 171, 174, 177,28 181, 184, 187,29 190, 193, 196,30 198, 201, 204,31 207, 209, 212,32 214, 217, 219,33 221, 223, 226,34 228, 230, 232,35 233, 235, 237,36 238, 240, 242,37 243, 244, 246,38 247, 248, 249,39 250, 251, 252,40 252, 253, 254,41 254, 255, 255,42 255, 255, 255,43 25644];4546Round( & number, const base) {47 if (number * 10 / base % 10 > 5) {48 number /= base;49 number += GetSign(number);50 } else51 number /= base;52}53GetSign(number) {54 return number < 0 ? -1 : 1;55}56stock pow(a, n) {57 if (!n)58 return 1;5960 new61 b = a;6263 while (--n != 0) {64 b *= a;65 }6667 return b;68}69ABS(value) {70 return value < 0 ? -value : value;71}72// Square root of integer73int_sqrt(s) {74 new x0 = s >> 1; // Initial estimate75 new x1;7677 // Sanity check78 if (x0) {79 x1 = (x0 + s / x0) >> 1; // Update8081 while (x1 < x0) // This also checks for cycle82 {83 x0 = x1;84 x1 = (x0 + s / x0) >> 1;85 }8687 return x0;88 } else {89 return s;90 }91}9293FixedSin (angle) {94 angle %= 360;95 if (angle <= 90) {96 return sin8LUT[angle];97 } else if (angle <= 180) {98 return sin8LUT[180 - angle];99 } else if (angle <= 270) {100 return -sin8LUT[angle - 180];101 } else {102 return -sin8LUT[360 - angle];103 }104}105106FixedCos (angle) {107 angle %= 360;108 if (angle <= 90) {109 return sin8LUT[90 - angle];110 } else if (angle <= 180) {111 return -sin8LUT[angle - 90];112 } else if (angle <= 270) {113 return -sin8LUT[270 - angle];114 } else {115 return sin8LUT[angle - 270];116 }117}118119// "Efficient approximations for the arctangent function", S. Rajan, Sichun Wang, R. Inkol, A. Joyal120Atan(x) {121 return ((PI_4_FIXED * x >> FP) - ((x * (ABS(x) - 256) >> FP) * (62 + (17 * ABS(x) >> FP)) >> FP)) * RAD_2_DEG >> FP;122}123124// More accurate but more expensive sqrt125sqrt(x) {126 if (x == 0) {127 return x;128 }129 new s, t;130 s = 1; t = x;131 // Decide the value of the first tentative132 while (s < t) {133 s <<= 1;134 t >>= 1;135 }136 do {137 t = s;138 // x1=(N / x0 + x0)/2 : recurrence formula139 s = (x / s + s) >> 1;140 } while (s < t);141 return t;142}143144Min(x, y) {145 return (x > y) ? (y) : (x);146}147148Max(x, y) {149 return (x > y) ? (x) : (y);150}151152Vector2D_Dot_Product(v1_x, v1_y, v2_x, v2_y) {153 return (v1_x * v2_x + v1_y * v2_y);154}155156Distance(x, y) {157 return sqrt(x * x + y * y);158}159160CheapDistance(x, y) {161 return (x * x + y * y);162}163164
Wrapped for easier reading. Turn wrap off to inspect exact line lengths.