+/TECS
git clone https://git.julia.blue/+/TECS
6e68fc9
v1.0
1/** 2 * A library of commonly used mathematical functions. 3 * Note: Jack compilers implement multiplication and division using OS method calls. 4 */ 5class Math { 6 static Array mask; 7 8 /** Initializes the library. */ 9 function void init() { 10 var int temp, i; 11 let mask = Array.new(16); 12 let temp = 1; 13 let i = 0; 14 while(i < 16){ 15 let mask[i] = temp; 16 let temp = temp + temp; 17 let i = i + 1; 18 } 19 return; 20 } 21 22 /** Returns the absolute value of x. */ 23 function int abs(int x) { 24 if(x < 0){ 25 let x = -x; 26 } 27 return x; 28 } 29 30 /** Returns the product of x and y. 31 * When a Jack compiler detects the multiplication operator '*' in the 32 * program's code, it handles it by invoking this method. In other words, 33 * the Jack expressions x*y and multiply(x,y) return the same value. 34 */ 35 function int multiply(int x, int y) { 36 var boolean negative; 37 var int sum, shiftedX, i; 38 let negative = false; 39 let sum = 0; 40 let i = 0; 41 if(x < 0){ 42 let negative = true; 43 } 44 if(y < 0){ 45 let negative = ~negative; 46 } 47 let x = Math.abs(x); 48 let y = Math.abs(y); 49 let shiftedX = x; 50 while(i < 16){ 51 if(~((mask[i] & y) = 0)){ 52 let sum = sum + shiftedX; 53 } 54 let shiftedX = shiftedX + shiftedX; 55 let i = i + 1; 56 } 57 if(negative){ 58 let sum = -sum; 59 } 60 return sum; 61 } 62 63 /** Returns the integer part of n/d. 64 * When a Jack compiler detects the multiplication operator '/' in the 65 * program's code, it handles it by invoking this method. In other words, 66 * the Jack expressions n/d and divide(n,d) return the same value. 67 */ 68 function int divide(int n, int d){ 69 var int result, a, b; 70 var boolean negative; 71 if(d = 0){ 72 do Sys.error(3); 73 } 74 let negative = false; 75 if(n < 0){ 76 let negative = true; 77 } 78 if(d < 0){ 79 let negative = ~negative; 80 } 81 let n = Math.abs(n); 82 let d = Math.abs(d); 83 let result = 0; 84 while(~(n < d)){ 85 let a = d; 86 let b = 1; 87 while((a + a) < n){ 88 let a = a + a; 89 let b = b + b; 90 } 91 let result = result + b; 92 let n = n - a; 93 } 94 if(negative){ 95 let result = -result; 96 } 97 return result; 98 } 99 100 /** Returns the integer part of the square root of x. */ 101 function int sqrt(int x) { 102 var int i, y, temp; 103 if(x < 0){ 104 do Sys.error(4); 105 } 106 let i = 7; 107 let y = 0; 108 while(i > -1){ 109 let temp = (y + mask[i]) * (y + mask[i]); 110 if(((temp < x) | (temp = x)) & (temp > 0)){ 111 let y = y + mask[i]; 112 } 113 let i = i - 1; 114 } 115 return y; 116 } 117 118 /** Returns the greater number. */ 119 function int max(int a, int b) { 120 if(a > b){ 121 return a; 122 } 123 return b; 124 } 125 126 /** Returns the smaller number. */ 127 function int min(int a, int b) { 128 if(a < b){ 129 return a; 130 } 131 return b; 132 } 133}