summaryrefslogtreecommitdiff
path: root/app/client/util/math.js
diff options
context:
space:
mode:
authorJules Laplace <julescarbon@gmail.com>2018-06-05 23:56:12 +0200
committerJules Laplace <julescarbon@gmail.com>2018-06-05 23:56:12 +0200
commit8c8e2e08d2ae89ba18ca05bab446e4642798dce2 (patch)
treed3153ba1fc32faa19d4094b2b5a18943f1e45dfa /app/client/util/math.js
parentc4dd63e487588cfa8e104a840af75854972b5ddb (diff)
pulling in wav2pix code
Diffstat (limited to 'app/client/util/math.js')
-rw-r--r--app/client/util/math.js52
1 files changed, 52 insertions, 0 deletions
diff --git a/app/client/util/math.js b/app/client/util/math.js
new file mode 100644
index 0000000..253bacd
--- /dev/null
+++ b/app/client/util/math.js
@@ -0,0 +1,52 @@
+export function mod(n,m){ return n-(m * Math.floor(n/m)) }
+export function clamp(n,a,b) { return n<a?a:n<b?n:b }
+export function norm(n,a,b) { return (n-a) / (b-a) }
+export function lerp(n,a,b) { return (b-a)*n+a }
+export function mix(n,a,b) { return a*(1-n)+b*n }
+export function randint(n) { return Math.floor(Math.random()*n) }
+export function randrange(a,b){ return Math.random() * (b-a) + a }
+export function randsign(){ return Math.random() >= 0.5 ? -1 : 1 }
+export function choice (a){ return a[ Math.floor(Math.random() * a.length) ] }
+export function lerp(n,a,b){ return (b-a)*n+a }
+export function angle(x0,y0,x1,y1){ return Math.atan2(y1-y0,x1-x0) }
+export function dist(x0,y0,x1,y1){ return Math.sqrt(Math.pow(x1-x0,2)+Math.pow(y1-y0,2)) }
+export function xor(a,b){ a=!!a; b=!!b; return (a||b) && !(a&&b) }
+export function quantize(a,b){ return Math.floor(a/b)*b }
+export function shuffle(a){
+ for (var i = a.length; i > 0; i--){
+ var r = randint(i)
+ var swap = a[i-1]
+ a[i-1] = a[r]
+ a[r] = swap
+ }
+ return a
+}
+// returns a gaussian random function with the given mean and stdev.
+export function gaussian(mean, stdev) {
+ let y2;
+ let use_last = false;
+ return () => {
+ let y1;
+ if (use_last) {
+ y1 = y2;
+ use_last = false;
+ }
+ else {
+ let x1, x2, w;
+ do {
+ x1 = 2.0 * Math.random() - 1.0;
+ x2 = 2.0 * Math.random() - 1.0;
+ w = x1 * x1 + x2 * x2;
+ } while( w >= 1.0);
+ w = Math.sqrt((-2.0 * Math.log(w))/w);
+ y1 = x1 * w;
+ y2 = x2 * w;
+ use_last = true;
+ }
+
+ let retval = mean + stdev * y1;
+ if (retval > 0)
+ return retval;
+ return -retval;
+ }
+}