forked from Khan/khan-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmath.js
More file actions
529 lines (443 loc) · 15.2 KB
/
math.js
File metadata and controls
529 lines (443 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
$.extend(KhanUtil, {
// Simplify formulas before display
cleanMath: function(expr) {
return typeof expr === "string" ?
KhanUtil.tmpl.cleanHTML(expr)
.replace(/\+\s*-/g, "- ")
.replace(/-\s*-/g, "+ ")
.replace(/\^1/g, "") :
expr;
},
// A simple random number picker
// Returns a random int in [0, num)
rand: function(num) {
return Math.floor(num * KhanUtil.random());
},
/* Returns an array of the digits of a nonnegative integer in reverse
* order: digits(376) = [6, 7, 3] */
digits: function(n) {
if (n === 0) {
return [0];
}
var list = [];
while (n > 0) {
list.push(n % 10);
n = Math.floor(n / 10);
}
return list;
},
// Similar to above digits, but in original order (not reversed)
integerToDigits: function(n) {
return KhanUtil.digits(n).reverse();
},
digitsToInteger: function(digits) {
var place = Math.floor(Math.pow(10, digits.length - 1));
var number = 0;
$.each(digits, function(index, digit) {
number += digit * place;
place /= 10;
});
return number;
},
padDigitsToNum: function(digits, num) {
digits = digits.slice(0);
while (digits.length < num) {
digits.push(0);
}
return digits;
},
placesLeftOfDecimal: ["one", "ten", "hundred", "thousand"],
placesRightOfDecimal: ["one", "tenth", "hundredth", "thousandth"],
powerToPlace: function(power) {
if (power < 0) {
return KhanUtil.placesRightOfDecimal[-1 * power];
} else {
return KhanUtil.placesLeftOfDecimal[power];
}
},
//Adds 0.001 because of floating points uncertainty so it errs on the side of going further away from 0
roundTowardsZero: function(x) {
if (x < 0) {
return Math.ceil(x - 0.001);
}
return Math.floor(x + 0.001);
},
factorial: function(x) {
if (x <= 1) {
return x;
} else {
return x * KhanUtil.factorial(x-1);
}
},
getGCD: function(a, b) {
if (arguments.length > 2) {
var rest = [].slice.call(arguments, 1);
return KhanUtil.getGCD(a, KhanUtil.getGCD.apply(KhanUtil, rest));
} else {
var mod;
a = Math.abs(a);
b = Math.abs(b);
while (b) {
mod = a % b;
a = b;
b = mod;
}
return a;
}
},
getLCM: function(a, b) {
if (arguments.length > 2) {
var rest = [].slice.call(arguments, 1);
return KhanUtil.getLCM(a, KhanUtil.getLCM.apply(KhanUtil, rest));
} else {
return Math.abs(a * b) / KhanUtil.getGCD(a, b);
}
},
primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97],
getPrime: function() {
return KhanUtil.primes[KhanUtil.rand(KhanUtil.primes.length)];
},
isPrime: function(n) {
if (n <= 1) {
return false;
} else if (n < 101) {
return !!$.grep(KhanUtil.primes, function(p, i) {
return Math.abs(p - n) <= 0.5;
}).length;
} else {
if (n <= 1 || n > 2 && n % 2 === 0) {
return false;
} else {
for (var i = 3, sqrt = Math.sqrt(n); i <= sqrt; i += 2) {
if (n % i === 0) {
return false;
}
}
}
return true;
}
},
isOdd: function(n) {
return n % 2 === 1;
},
isEven: function(n) {
return n % 2 === 0;
},
getOddComposite: function(min, max) {
if (min === undefined) {
min = 0;
}
if (max === undefined) {
max = 100;
}
var oddComposites = [9, 15, 21, 25, 27, 33, 35, 39, 45, 49, 51, 55];
oddComposites = oddComposites.concat([57, 63, 65, 69, 75, 77, 81, 85, 87, 91, 93, 95, 99]);
var result = -1;
while (result < min || result > max) {
result = oddComposites[KhanUtil.rand(oddComposites.length)];
}
return result;
},
getEvenComposite: function(min, max) {
if (min === undefined) {
min = 0;
}
if (max === undefined) {
max = 100;
}
var evenComposites = [4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26];
evenComposites = evenComposites.concat([28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48]);
evenComposites = evenComposites.concat([50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72]);
evenComposites = evenComposites.concat([74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]);
var result = -1;
while (result < min || result > max) {
result = evenComposites[KhanUtil.rand(evenComposites.length)];
}
return result;
},
getComposite: function() {
if (KhanUtil.randRange(0, 1)) {
return KhanUtil.getEvenComposite();
} else {
return KhanUtil.getOddComposite();
}
},
getPrimeFactorization: function(number) {
if (number === 1) {
return [];
} else if (KhanUtil.isPrime(number)) {
return [number];
}
var maxf = Math.sqrt(number);
for (var f = 2; f <= maxf; f++) {
if (number % f === 0) {
return $.merge(KhanUtil.getPrimeFactorization(f), KhanUtil.getPrimeFactorization(number / f));
}
}
},
getFactors: function(number) {
var factors = [],
ins = function(n) {
if (_(factors).indexOf(n) === -1) {
factors.push(n);
}
};
var maxf2 = number;
for (var f = 1; f * f <= maxf2; f++) {
if (number % f === 0) {
ins(f);
ins(number / f);
}
}
return KhanUtil.sortNumbers(factors);
},
// Get a random factor of a composite number which is not 1 or that number
getNontrivialFactor: function(number) {
var factors = KhanUtil.getFactors(number);
return factors[KhanUtil.randRange(1, factors.length - 2)];
},
getMultiples: function(number, upperLimit) {
var multiples = [];
for (var i = 1; i * number <= upperLimit; i++) {
multiples.push(i * number);
}
return multiples;
},
// splitRadical(24) gives [2, 6] to mean 2 sqrt(6)
splitRadical: function(n) {
if (n === 0) {
return [0, 1];
}
var coefficient = 1;
var radical = n;
for (var i = 2; i * i <= n; i++) {
while (radical % (i * i) === 0) {
radical /= i * i;
coefficient *= i;
}
}
return [coefficient, radical];
},
// randRange(min, max) - Get a random integer between min and max, inclusive
// randRange(min, max, count) - Get count random integers
// randRange(min, max, rows, cols) - Get a rows x cols matrix of random integers
// randRange(min, max, x, y, z) - You get the point...
randRange: function(min, max) {
var dimensions = [].slice.call(arguments, 2);
if (dimensions.length === 0) {
return Math.floor(KhanUtil.rand(max - min + 1)) + min;
} else {
var args = [min, max].concat(dimensions.slice(1));
return $.map(new Array(dimensions[0]), function() {
return [KhanUtil.randRange.apply(null, args)];
});
}
},
// Get an array of unique random numbers between min and max
randRangeUnique: function(min, max, count) {
if (count == null) {
return KhanUtil.randRange(min, max);
} else {
var toReturn = [];
for (var i = min; i < max; i++) {
toReturn.push(i);
}
return KhanUtil.shuffle(toReturn, count);
}
},
// Get an array of unique random numbers between min and max,
// that ensures that none of the integers in the array are 0.
randRangeUniqueNonZero: function(min, max, count) {
if (count == null) {
return KhanUtil.randRangeNonZero(min, max);
} else {
var toReturn = [];
for (var i = min; i < max; i++) {
if (i === 0) {
continue;
}
toReturn.push(i);
}
return KhanUtil.shuffle(toReturn, count);
}
},
// Get a random integer between min and max with a perc chance of hitting
// target (which is assumed to be in the range, but it doesn't have to be).
randRangeWeighted: function(min, max, target, perc) {
if (KhanUtil.random() < perc || (target === min && target === max)) {
return target;
} else {
return KhanUtil.randRangeExclude(min, max, [target]);
}
},
// Get a random integer between min and max that is never any of the values
// in the excludes array.
randRangeExclude: function(min, max, excludes) {
var result;
do {
result = KhanUtil.randRange(min, max);
} while (_(excludes).indexOf(result) !== -1);
return result;
},
// Get a random integer between min and max with a perc chance of hitting
// target (which is assumed to be in the range, but it doesn't have to be).
// It never returns any of the values in the excludes array.
randRangeWeightedExclude: function(min, max, target, perc, excludes) {
var result;
do {
result = KhanUtil.randRangeWeighted(min, max, target, perc);
} while (_(excludes).indexOf(result) !== -1);
return result;
},
// From limits_1
randRangeNonZero: function(min, max) {
return KhanUtil.randRangeExclude(min, max, [0]);
},
// Returns a random member of the given array
// If a count is passed, it gives an array of random members of the given array
randFromArray: function(arr, count) {
if (count == null) {
return arr[KhanUtil.rand(arr.length)];
} else {
return $.map(new Array(count), function() {
return KhanUtil.randFromArray(arr);
});
}
},
// Returns a random member of the given array that is never any of the values
// in the excludes array.
randFromArrayExclude: function(arr, excludes) {
var cleanArr = [];
for (var i = 0; i < arr.length; i++) {
if (_(excludes).indexOf(arr[i]) === -1) {
cleanArr.push(arr[i]);
}
}
return KhanUtil.randFromArray(cleanArr);
},
// Round a number to the nearest increment
// E.g., if increment = 30 and num = 40, return 30. if increment = 30 and num = 45, return 60.
roundToNearest: function(increment, num) {
return Math.round(num / increment) * increment;
},
// Round a number to a certain number of decimal places
roundTo: function(precision, num) {
var factor = Math.pow(10, precision).toFixed(5);
return Math.round((num * factor).toFixed(5)) / factor;
},
floorTo: function(precision, num) {
var factor = Math.pow(10, precision).toFixed(5);
return Math.floor((num * factor).toFixed(5)) / factor;
},
ceilTo: function(precision, num) {
var factor = Math.pow(10, precision).toFixed(5);
return Math.ceil((num * factor).toFixed(5)) / factor;
},
// toFraction(4/8) => [1, 2]
// toFraction(0.666) => [333, 500]
// toFraction(0.666, 0.001) => [2, 3]
//
// tolerance can't be bigger than 1, sorry
toFraction: function(decimal, tolerance) {
if (tolerance == null) {
tolerance = Math.pow(2, -46);
}
if (decimal < 0 || decimal > 1) {
var fract = decimal % 1;
fract += (fract < 0 ? 1 : 0);
var nd = KhanUtil.toFraction(fract, tolerance);
nd[0] += Math.round(decimal - fract) * nd[1];
return nd;
} else if (Math.abs(Math.round(Number(decimal)) - decimal) <= tolerance) {
return [Math.round(decimal), 1];
} else {
var loN = 0, loD = 1, hiN = 1, hiD = 1, midN = 1, midD = 2;
while (1) {
if (Math.abs(Number(midN / midD) - decimal) <= tolerance) {
return [midN, midD];
} else if (midN / midD < decimal) {
loN = midN;
loD = midD;
} else {
hiN = midN;
hiD = midD;
}
midN = loN + hiN;
midD = loD + hiD;
}
}
},
// Shuffle an array using a Fischer-Yates shuffle
// If count is passed, returns an random sublist of that size
shuffle: function(array, count) {
array = [].slice.call(array, 0);
var beginning = typeof count === "undefined" || count > array.length ? 0 : array.length - count;
for (var top = array.length; top > beginning; top--) {
var newEnd = Math.floor(KhanUtil.random() * top),
tmp = array[newEnd];
array[newEnd] = array[top - 1];
array[top - 1] = tmp;
}
return array.slice(beginning);
},
sortNumbers: function(array) {
return array.slice(0).sort(function(a, b) {
return a - b;
});
},
// From limits_1
truncate_to_max: function(num, digits) {
return parseFloat(num.toFixed(digits));
},
//Gives -1 or 1 so you can multiply to restore the sign of a number
restoreSign: function(num) {
num = parseFloat(num);
if (num < 0) {
return -1;
}
return 1;
},
// Checks if a number or string representation thereof is an integer
isInt: function(num) {
return parseFloat(num) === parseInt(num, 10) && !isNaN(num);
},
/**
* Add LaTeX color markup to a given value.
*/
colorMarkup: function(val, color) {
return "\\color{" + color + "}{" + val + "}";
},
/**
* Like _.contains except using _.isEqual to verify if item is present.
* (Works for lists of non-primitive values.)
*/
contains: function(list, item) {
return _.any(list, function(elem) {
if (_.isEqual(item, elem)) {
return true;
}
return false;
});
},
tagMarkup: function(val, tag, attr) {
attr = attr || "";
return "<" + tag + " " + attr + ">" + val + "</" + tag + ">";
},
/**
* Add hint color markup to a given value
*/
hintColorMarkup: function(val, colorName) {
var hintCSS = "class='hint_" + colorName + "'";
return KhanUtil.tagMarkup(val, "span", hintCSS);
},
BLUE: "#6495ED",
ORANGE: "#FFA500",
PINK: "#FF00AF",
GREEN: "#28AE7B",
PURPLE: "#9D38BD",
RED: "#DF0030",
GRAY: "gray",
BLACK: "black",
BACKGROUND: "#FAFAFA"
});