diff options
Diffstat (limited to 'js/dojo/dojox/math')
| -rw-r--r-- | js/dojo/dojox/math/BigInteger-ext.js | 657 | ||||
| -rw-r--r-- | js/dojo/dojox/math/BigInteger.js | 590 | ||||
| -rw-r--r-- | js/dojo/dojox/math/README | 40 | ||||
| -rw-r--r-- | js/dojo/dojox/math/_base.js | 163 | ||||
| -rw-r--r-- | js/dojo/dojox/math/curves.js | 195 | ||||
| -rw-r--r-- | js/dojo/dojox/math/matrix.js | 296 | ||||
| -rw-r--r-- | js/dojo/dojox/math/random/Secure.js | 99 | ||||
| -rw-r--r-- | js/dojo/dojox/math/random/Simple.js | 25 | ||||
| -rw-r--r-- | js/dojo/dojox/math/random/prng4.js | 60 | ||||
| -rw-r--r-- | js/dojo/dojox/math/round.js | 66 | ||||
| -rw-r--r-- | js/dojo/dojox/math/stats.js | 195 |
11 files changed, 2386 insertions, 0 deletions
diff --git a/js/dojo/dojox/math/BigInteger-ext.js b/js/dojo/dojox/math/BigInteger-ext.js new file mode 100644 index 0000000..ce336fc --- /dev/null +++ b/js/dojo/dojox/math/BigInteger-ext.js @@ -0,0 +1,657 @@ +//>>built +// AMD-ID "dojox/math/BigInteger-ext" +define("dojox/math/BigInteger-ext", ["dojo", "dojox", "dojox/math/BigInteger"], function(dojo, dojox) { + dojo.experimental("dojox.math.BigInteger-ext"); + +// Contributed under CLA by Tom Wu + +// Extended JavaScript BN functions, required for RSA private ops. + var BigInteger = dojox.math.BigInteger, + nbi = BigInteger._nbi, nbv = BigInteger._nbv, + nbits = BigInteger._nbits, + Montgomery = BigInteger._Montgomery; + + // (public) + function bnClone() { var r = nbi(); this._copyTo(r); return r; } + + // (public) return value as integer + function bnIntValue() { + if(this.s < 0) { + if(this.t == 1) return this[0]-this._DV; + else if(this.t == 0) return -1; + } + else if(this.t == 1) return this[0]; + else if(this.t == 0) return 0; + // assumes 16 < DB < 32 + return ((this[1]&((1<<(32-this._DB))-1))<<this._DB)|this[0]; + } + + // (public) return value as byte + function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; } + + // (public) return value as short (assumes DB>=16) + function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } + + // (protected) return x s.t. r^x < DV + function bnpChunkSize(r) { return Math.floor(Math.LN2*this._DB/Math.log(r)); } + + // (public) 0 if this == 0, 1 if this > 0 + function bnSigNum() { + if(this.s < 0) return -1; + else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; + else return 1; + } + + // (protected) convert to radix string + function bnpToRadix(b) { + if(b == null) b = 10; + if(this.signum() == 0 || b < 2 || b > 36) return "0"; + var cs = this._chunkSize(b); + var a = Math.pow(b,cs); + var d = nbv(a), y = nbi(), z = nbi(), r = ""; + this._divRemTo(d,y,z); + while(y.signum() > 0) { + r = (a+z.intValue()).toString(b).substr(1) + r; + y._divRemTo(d,y,z); + } + return z.intValue().toString(b) + r; + } + + // (protected) convert from radix string + function bnpFromRadix(s,b) { + this._fromInt(0); + if(b == null) b = 10; + var cs = this._chunkSize(b); + var d = Math.pow(b,cs), mi = false, j = 0, w = 0; + for(var i = 0; i < s.length; ++i) { + var x = intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-" && this.signum() == 0) mi = true; + continue; + } + w = b*w+x; + if(++j >= cs) { + this._dMultiply(d); + this._dAddOffset(w,0); + j = 0; + w = 0; + } + } + if(j > 0) { + this._dMultiply(Math.pow(b,j)); + this._dAddOffset(w,0); + } + if(mi) BigInteger.ZERO._subTo(this,this); + } + + // (protected) alternate constructor + function bnpFromNumber(a,b,c) { + if("number" == typeof b) { + // new BigInteger(int,int,RNG) + if(a < 2) this._fromInt(1); + else { + this._fromNumber(a,c); + if(!this.testBit(a-1)) // force MSB set + this._bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); + if(this._isEven()) this._dAddOffset(1,0); // force odd + while(!this.isProbablePrime(b)) { + this._dAddOffset(2,0); + if(this.bitLength() > a) this._subTo(BigInteger.ONE.shiftLeft(a-1),this); + } + } + } + else { + // new BigInteger(int,RNG) + var x = [], t = a&7; + x.length = (a>>3)+1; + b.nextBytes(x); + if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0; + this._fromString(x,256); + } + } + + // (public) convert to bigendian byte array + function bnToByteArray() { + var i = this.t, r = []; + r[0] = this.s; + var p = this._DB-(i*this._DB)%8, d, k = 0; + if(i-- > 0) { + if(p < this._DB && (d = this[i]>>p) != (this.s&this._DM)>>p) + r[k++] = d|(this.s<<(this._DB-p)); + while(i >= 0) { + if(p < 8) { + d = (this[i]&((1<<p)-1))<<(8-p); + d |= this[--i]>>(p+=this._DB-8); + } + else { + d = (this[i]>>(p-=8))&0xff; + if(p <= 0) { p += this._DB; --i; } + } + if((d&0x80) != 0) d |= -256; + if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; + if(k > 0 || d != this.s) r[k++] = d; + } + } + return r; + } + + function bnEquals(a) { return(this.compareTo(a)==0); } + function bnMin(a) { return(this.compareTo(a)<0)?this:a; } + function bnMax(a) { return(this.compareTo(a)>0)?this:a; } + + // (protected) r = this op a (bitwise) + function bnpBitwiseTo(a,op,r) { + var i, f, m = Math.min(a.t,this.t); + for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); + if(a.t < this.t) { + f = a.s&this._DM; + for(i = m; i < this.t; ++i) r[i] = op(this[i],f); + r.t = this.t; + } + else { + f = this.s&this._DM; + for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); + r.t = a.t; + } + r.s = op(this.s,a.s); + r._clamp(); + } + + // (public) this & a + function op_and(x,y) { return x&y; } + function bnAnd(a) { var r = nbi(); this._bitwiseTo(a,op_and,r); return r; } + + // (public) this | a + function op_or(x,y) { return x|y; } + function bnOr(a) { var r = nbi(); this._bitwiseTo(a,op_or,r); return r; } + + // (public) this ^ a + function op_xor(x,y) { return x^y; } + function bnXor(a) { var r = nbi(); this._bitwiseTo(a,op_xor,r); return r; } + + // (public) this & ~a + function op_andnot(x,y) { return x&~y; } + function bnAndNot(a) { var r = nbi(); this._bitwiseTo(a,op_andnot,r); return r; } + + // (public) ~this + function bnNot() { + var r = nbi(); + for(var i = 0; i < this.t; ++i) r[i] = this._DM&~this[i]; + r.t = this.t; + r.s = ~this.s; + return r; + } + + // (public) this << n + function bnShiftLeft(n) { + var r = nbi(); + if(n < 0) this._rShiftTo(-n,r); else this._lShiftTo(n,r); + return r; + } + + // (public) this >> n + function bnShiftRight(n) { + var r = nbi(); + if(n < 0) this._lShiftTo(-n,r); else this._rShiftTo(n,r); + return r; + } + + // return index of lowest 1-bit in x, x < 2^31 + function lbit(x) { + if(x == 0) return -1; + var r = 0; + if((x&0xffff) == 0) { x >>= 16; r += 16; } + if((x&0xff) == 0) { x >>= 8; r += 8; } + if((x&0xf) == 0) { x >>= 4; r += 4; } + if((x&3) == 0) { x >>= 2; r += 2; } + if((x&1) == 0) ++r; + return r; + } + + // (public) returns index of lowest 1-bit (or -1 if none) + function bnGetLowestSetBit() { + for(var i = 0; i < this.t; ++i) + if(this[i] != 0) return i*this._DB+lbit(this[i]); + if(this.s < 0) return this.t*this._DB; + return -1; + } + + // return number of 1 bits in x + function cbit(x) { + var r = 0; + while(x != 0) { x &= x-1; ++r; } + return r; + } + + // (public) return number of set bits + function bnBitCount() { + var r = 0, x = this.s&this._DM; + for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); + return r; + } + + // (public) true iff nth bit is set + function bnTestBit(n) { + var j = Math.floor(n/this._DB); + if(j >= this.t) return(this.s!=0); + return((this[j]&(1<<(n%this._DB)))!=0); + } + + // (protected) this op (1<<n) + function bnpChangeBit(n,op) { + var r = BigInteger.ONE.shiftLeft(n); + this._bitwiseTo(r,op,r); + return r; + } + + // (public) this | (1<<n) + function bnSetBit(n) { return this._changeBit(n,op_or); } + + // (public) this & ~(1<<n) + function bnClearBit(n) { return this._changeBit(n,op_andnot); } + + // (public) this ^ (1<<n) + function bnFlipBit(n) { return this._changeBit(n,op_xor); } + + // (protected) r = this + a + function bnpAddTo(a,r) { + var i = 0, c = 0, m = Math.min(a.t,this.t); + while(i < m) { + c += this[i]+a[i]; + r[i++] = c&this._DM; + c >>= this._DB; + } + if(a.t < this.t) { + c += a.s; + while(i < this.t) { + c += this[i]; + r[i++] = c&this._DM; + c >>= this._DB; + } + c += this.s; + } + else { + c += this.s; + while(i < a.t) { + c += a[i]; + r[i++] = c&this._DM; + c >>= this._DB; + } + c += a.s; + } + r.s = (c<0)?-1:0; + if(c > 0) r[i++] = c; + else if(c < -1) r[i++] = this._DV+c; + r.t = i; + r._clamp(); + } + + // (public) this + a + function bnAdd(a) { var r = nbi(); this._addTo(a,r); return r; } + + // (public) this - a + function bnSubtract(a) { var r = nbi(); this._subTo(a,r); return r; } + + // (public) this * a + function bnMultiply(a) { var r = nbi(); this._multiplyTo(a,r); return r; } + + // (public) this / a + function bnDivide(a) { var r = nbi(); this._divRemTo(a,r,null); return r; } + + // (public) this % a + function bnRemainder(a) { var r = nbi(); this._divRemTo(a,null,r); return r; } + + // (public) [this/a,this%a] + function bnDivideAndRemainder(a) { + var q = nbi(), r = nbi(); + this._divRemTo(a,q,r); + return [q, r]; + } + + // (protected) this *= n, this >= 0, 1 < n < DV + function bnpDMultiply(n) { + this[this.t] = this.am(0,n-1,this,0,0,this.t); + ++this.t; + this._clamp(); + } + + // (protected) this += n << w words, this >= 0 + function bnpDAddOffset(n,w) { + while(this.t <= w) this[this.t++] = 0; + this[w] += n; + while(this[w] >= this._DV) { + this[w] -= this._DV; + if(++w >= this.t) this[this.t++] = 0; + ++this[w]; + } + } + + // A "null" reducer + function NullExp() {} + function nNop(x) { return x; } + function nMulTo(x,y,r) { x._multiplyTo(y,r); } + function nSqrTo(x,r) { x._squareTo(r); } + + NullExp.prototype.convert = nNop; + NullExp.prototype.revert = nNop; + NullExp.prototype.mulTo = nMulTo; + NullExp.prototype.sqrTo = nSqrTo; + + // (public) this^e + function bnPow(e) { return this._exp(e,new NullExp()); } + + // (protected) r = lower n words of "this * a", a.t <= n + // "this" should be the larger one if appropriate. + function bnpMultiplyLowerTo(a,n,r) { + var i = Math.min(this.t+a.t,n); + r.s = 0; // assumes a,this >= 0 + r.t = i; + while(i > 0) r[--i] = 0; + var j; + for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); + for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); + r._clamp(); + } + + // (protected) r = "this * a" without lower n words, n > 0 + // "this" should be the larger one if appropriate. + function bnpMultiplyUpperTo(a,n,r) { + --n; + var i = r.t = this.t+a.t-n; + r.s = 0; // assumes a,this >= 0 + while(--i >= 0) r[i] = 0; + for(i = Math.max(n-this.t,0); i < a.t; ++i) + r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); + r._clamp(); + r._drShiftTo(1,r); + } + + // Barrett modular reduction + function Barrett(m) { + // setup Barrett + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE._dlShiftTo(2*m.t,this.r2); + this.mu = this.r2.divide(m); + this.m = m; + } + + function barrettConvert(x) { + if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); + else if(x.compareTo(this.m) < 0) return x; + else { var r = nbi(); x._copyTo(r); this.reduce(r); return r; } + } + + function barrettRevert(x) { return x; } + + // x = x mod m (HAC 14.42) + function barrettReduce(x) { + x._drShiftTo(this.m.t-1,this.r2); + if(x.t > this.m.t+1) { x.t = this.m.t+1; x._clamp(); } + this.mu._multiplyUpperTo(this.r2,this.m.t+1,this.q3); + this.m._multiplyLowerTo(this.q3,this.m.t+1,this.r2); + while(x.compareTo(this.r2) < 0) x._dAddOffset(1,this.m.t+1); + x._subTo(this.r2,x); + while(x.compareTo(this.m) >= 0) x._subTo(this.m,x); + } + + // r = x^2 mod m; x != r + function barrettSqrTo(x,r) { x._squareTo(r); this.reduce(r); } + + // r = x*y mod m; x,y != r + function barrettMulTo(x,y,r) { x._multiplyTo(y,r); this.reduce(r); } + + Barrett.prototype.convert = barrettConvert; + Barrett.prototype.revert = barrettRevert; + Barrett.prototype.reduce = barrettReduce; + Barrett.prototype.mulTo = barrettMulTo; + Barrett.prototype.sqrTo = barrettSqrTo; + + // (public) this^e % m (HAC 14.85) + function bnModPow(e,m) { + var i = e.bitLength(), k, r = nbv(1), z; + if(i <= 0) return r; + else if(i < 18) k = 1; + else if(i < 48) k = 3; + else if(i < 144) k = 4; + else if(i < 768) k = 5; + else k = 6; + if(i < 8) + z = new Classic(m); + else if(m._isEven()) + z = new Barrett(m); + else + z = new Montgomery(m); + + // precomputation + var g = [], n = 3, k1 = k-1, km = (1<<k)-1; + g[1] = z.convert(this); + if(k > 1) { + var g2 = nbi(); + z.sqrTo(g[1],g2); + while(n <= km) { + g[n] = nbi(); + z.mulTo(g2,g[n-2],g[n]); + n += 2; + } + } + + var j = e.t-1, w, is1 = true, r2 = nbi(), t; + i = nbits(e[j])-1; + while(j >= 0) { + if(i >= k1) w = (e[j]>>(i-k1))&km; + else { + w = (e[j]&((1<<(i+1))-1))<<(k1-i); + if(j > 0) w |= e[j-1]>>(this._DB+i-k1); + } + + n = k; + while((w&1) == 0) { w >>= 1; --n; } + if((i -= n) < 0) { i += this._DB; --j; } + if(is1) { // ret == 1, don't bother squaring or multiplying it + g[w]._copyTo(r); + is1 = false; + } + else { + while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } + if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } + z.mulTo(r2,g[w],r); + } + + while(j >= 0 && (e[j]&(1<<i)) == 0) { + z.sqrTo(r,r2); t = r; r = r2; r2 = t; + if(--i < 0) { i = this._DB-1; --j; } + } + } + return z.revert(r); + } + + // (public) gcd(this,a) (HAC 14.54) + function bnGCD(a) { + var x = (this.s<0)?this.negate():this.clone(); + var y = (a.s<0)?a.negate():a.clone(); + if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } + var i = x.getLowestSetBit(), g = y.getLowestSetBit(); + if(g < 0) return x; + if(i < g) g = i; + if(g > 0) { + x._rShiftTo(g,x); + y._rShiftTo(g,y); + } + while(x.signum() > 0) { + if((i = x.getLowestSetBit()) > 0) x._rShiftTo(i,x); + if((i = y.getLowestSetBit()) > 0) y._rShiftTo(i,y); + if(x.compareTo(y) >= 0) { + x._subTo(y,x); + x._rShiftTo(1,x); + } + else { + y._subTo(x,y); + y._rShiftTo(1,y); + } + } + if(g > 0) y._lShiftTo(g,y); + return y; + } + + // (protected) this % n, n < 2^26 + function bnpModInt(n) { + if(n <= 0) return 0; + var d = this._DV%n, r = (this.s<0)?n-1:0; + if(this.t > 0) + if(d == 0) r = this[0]%n; + else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; + return r; + } + + // (public) 1/this % m (HAC 14.61) + function bnModInverse(m) { + var ac = m._isEven(); + if((this._isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; + var u = m.clone(), v = this.clone(); + var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); + while(u.signum() != 0) { + while(u._isEven()) { + u._rShiftTo(1,u); + if(ac) { + if(!a._isEven() || !b._isEven()) { a._addTo(this,a); b._subTo(m,b); } + a._rShiftTo(1,a); + } + else if(!b._isEven()) b._subTo(m,b); + b._rShiftTo(1,b); + } + while(v._isEven()) { + v._rShiftTo(1,v); + if(ac) { + if(!c._isEven() || !d._isEven()) { c._addTo(this,c); d._subTo(m,d); } + c._rShiftTo(1,c); + } + else if(!d._isEven()) d._subTo(m,d); + d._rShiftTo(1,d); + } + if(u.compareTo(v) >= 0) { + u._subTo(v,u); + if(ac) a._subTo(c,a); + b._subTo(d,b); + } + else { + v._subTo(u,v); + if(ac) c._subTo(a,c); + d._subTo(b,d); + } + } + if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; + if(d.compareTo(m) >= 0) return d.subtract(m); + if(d.signum() < 0) d._addTo(m,d); else return d; + if(d.signum() < 0) return d.add(m); else return d; + } + + var lowprimes = [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,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; + var lplim = (1<<26)/lowprimes[lowprimes.length-1]; + + // (public) test primality with certainty >= 1-.5^t + function bnIsProbablePrime(t) { + var i, x = this.abs(); + if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { + for(i = 0; i < lowprimes.length; ++i) + if(x[0] == lowprimes[i]) return true; + return false; + } + if(x._isEven()) return false; + i = 1; + while(i < lowprimes.length) { + var m = lowprimes[i], j = i+1; + while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x._modInt(m); + while(i < j) if(m%lowprimes[i++] == 0) return false; + } + return x._millerRabin(t); + } + + // (protected) true if probably prime (HAC 4.24, Miller-Rabin) + function bnpMillerRabin(t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if(k <= 0) return false; + var r = n1.shiftRight(k); + t = (t+1)>>1; + if(t > lowprimes.length) t = lowprimes.length; + var a = nbi(); + for(var i = 0; i < t; ++i) { + a._fromInt(lowprimes[i]); + var y = a.modPow(r,this); + if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while(j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2,this); + if(y.compareTo(BigInteger.ONE) == 0) return false; + } + if(y.compareTo(n1) != 0) return false; + } + } + return true; + } + + dojo.extend(BigInteger, { + // protected + _chunkSize: bnpChunkSize, + _toRadix: bnpToRadix, + _fromRadix: bnpFromRadix, + _fromNumber: bnpFromNumber, + _bitwiseTo: bnpBitwiseTo, + _changeBit: bnpChangeBit, + _addTo: bnpAddTo, + _dMultiply: bnpDMultiply, + _dAddOffset: bnpDAddOffset, + _multiplyLowerTo: bnpMultiplyLowerTo, + _multiplyUpperTo: bnpMultiplyUpperTo, + _modInt: bnpModInt, + _millerRabin: bnpMillerRabin, + + // public + clone: bnClone, + intValue: bnIntValue, + byteValue: bnByteValue, + shortValue: bnShortValue, + signum: bnSigNum, + toByteArray: bnToByteArray, + equals: bnEquals, + min: bnMin, + max: bnMax, + and: bnAnd, + or: bnOr, + xor: bnXor, + andNot: bnAndNot, + not: bnNot, + shiftLeft: bnShiftLeft, + shiftRight: bnShiftRight, + getLowestSetBit: bnGetLowestSetBit, + bitCount: bnBitCount, + testBit: bnTestBit, + setBit: bnSetBit, + clearBit: bnClearBit, + flipBit: bnFlipBit, + add: bnAdd, + subtract: bnSubtract, + multiply: bnMultiply, + divide: bnDivide, + remainder: bnRemainder, + divideAndRemainder: bnDivideAndRemainder, + modPow: bnModPow, + modInverse: bnModInverse, + pow: bnPow, + gcd: bnGCD, + isProbablePrime: bnIsProbablePrime + }); + + // BigInteger interfaces not implemented in jsbn: + + // BigInteger(int signum, byte[] magnitude) + // double doubleValue() + // float floatValue() + // int hashCode() + // long longValue() + // static BigInteger valueOf(long val) + + return dojox.math.BigInteger; +}); diff --git a/js/dojo/dojox/math/BigInteger.js b/js/dojo/dojox/math/BigInteger.js new file mode 100644 index 0000000..ef40310 --- /dev/null +++ b/js/dojo/dojox/math/BigInteger.js @@ -0,0 +1,590 @@ +//>>built +// AMD-ID "dojox/math/BigInteger" +define("dojox/math/BigInteger", ["dojo", "dojox"], function(dojo, dojox) { + + dojo.getObject("math.BigInteger", true, dojox); + dojo.experimental("dojox.math.BigInteger"); + +// Contributed under CLA by Tom Wu <tjw@cs.Stanford.EDU> +// See http://www-cs-students.stanford.edu/~tjw/jsbn/ for details. + +// Basic JavaScript BN library - subset useful for RSA encryption. +// The API for dojox.math.BigInteger closely resembles that of the java.math.BigInteger class in Java. + + // Bits per digit + var dbits; + + // JavaScript engine analysis + var canary = 0xdeadbeefcafe; + var j_lm = ((canary&0xffffff)==0xefcafe); + + // (public) Constructor + function BigInteger(a,b,c) { + if(a != null) + if("number" == typeof a) this._fromNumber(a,b,c); + else if(!b && "string" != typeof a) this._fromString(a,256); + else this._fromString(a,b); + } + + // return new, unset BigInteger + function nbi() { return new BigInteger(null); } + + // am: Compute w_j += (x*this_i), propagate carries, + // c is initial carry, returns final carry. + // c < 3*dvalue, x < 2*dvalue, this_i < dvalue + // We need to select the fastest one that works in this environment. + + // am1: use a single mult and divide to get the high bits, + // max digit bits should be 26 because + // max internal value = 2*dvalue^2-2*dvalue (< 2^53) + function am1(i,x,w,j,c,n) { + while(--n >= 0) { + var v = x*this[i++]+w[j]+c; + c = Math.floor(v/0x4000000); + w[j++] = v&0x3ffffff; + } + return c; + } + // am2 avoids a big mult-and-extract completely. + // Max digit bits should be <= 30 because we do bitwise ops + // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) + function am2(i,x,w,j,c,n) { + var xl = x&0x7fff, xh = x>>15; + while(--n >= 0) { + var l = this[i]&0x7fff; + var h = this[i++]>>15; + var m = xh*l+h*xl; + l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); + c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); + w[j++] = l&0x3fffffff; + } + return c; + } + // Alternately, set max digit bits to 28 since some + // browsers slow down when dealing with 32-bit numbers. + function am3(i,x,w,j,c,n) { + var xl = x&0x3fff, xh = x>>14; + while(--n >= 0) { + var l = this[i]&0x3fff; + var h = this[i++]>>14; + var m = xh*l+h*xl; + l = xl*l+((m&0x3fff)<<14)+w[j]+c; + c = (l>>28)+(m>>14)+xh*h; + w[j++] = l&0xfffffff; + } + return c; + } + if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { + BigInteger.prototype.am = am2; + dbits = 30; + } + else if(j_lm && (navigator.appName != "Netscape")) { + BigInteger.prototype.am = am1; + dbits = 26; + } + else { // Mozilla/Netscape seems to prefer am3 + BigInteger.prototype.am = am3; + dbits = 28; + } + + var BI_FP = 52; + + // Digit conversions + var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; + var BI_RC = []; + var rr,vv; + rr = "0".charCodeAt(0); + for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; + rr = "a".charCodeAt(0); + for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + rr = "A".charCodeAt(0); + for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + + function int2char(n) { return BI_RM.charAt(n); } + function intAt(s,i) { + var c = BI_RC[s.charCodeAt(i)]; + return (c==null)?-1:c; + } + + // (protected) copy this to r + function bnpCopyTo(r) { + for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; + r.t = this.t; + r.s = this.s; + } + + // (protected) set from integer value x, -DV <= x < DV + function bnpFromInt(x) { + this.t = 1; + this.s = (x<0)?-1:0; + if(x > 0) this[0] = x; + else if(x < -1) this[0] = x+_DV; + else this.t = 0; + } + + // return bigint initialized to value + function nbv(i) { var r = nbi(); r._fromInt(i); return r; } + + // (protected) set from string and radix + function bnpFromString(s,b) { + var k; + if(b == 16) k = 4; + else if(b == 8) k = 3; + else if(b == 256) k = 8; // byte array + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else { this.fromRadix(s,b); return; } + this.t = 0; + this.s = 0; + var i = s.length, mi = false, sh = 0; + while(--i >= 0) { + var x = (k==8)?s[i]&0xff:intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-") mi = true; + continue; + } + mi = false; + if(sh == 0) + this[this.t++] = x; + else if(sh+k > this._DB) { + this[this.t-1] |= (x&((1<<(this._DB-sh))-1))<<sh; + this[this.t++] = (x>>(this._DB-sh)); + } + else + this[this.t-1] |= x<<sh; + sh += k; + if(sh >= this._DB) sh -= this._DB; + } + if(k == 8 && (s[0]&0x80) != 0) { + this.s = -1; + if(sh > 0) this[this.t-1] |= ((1<<(this._DB-sh))-1)<<sh; + } + this._clamp(); + if(mi) BigInteger.ZERO._subTo(this,this); + } + + // (protected) clamp off excess high words + function bnpClamp() { + var c = this.s&this._DM; + while(this.t > 0 && this[this.t-1] == c) --this.t; + } + + // (public) return string representation in given radix + function bnToString(b) { + if(this.s < 0) return "-"+this.negate().toString(b); + var k; + if(b == 16) k = 4; + else if(b == 8) k = 3; + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else return this._toRadix(b); + var km = (1<<k)-1, d, m = false, r = "", i = this.t; + var p = this._DB-(i*this._DB)%k; + if(i-- > 0) { + if(p < this._DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } + while(i >= 0) { + if(p < k) { + d = (this[i]&((1<<p)-1))<<(k-p); + d |= this[--i]>>(p+=this._DB-k); + } + else { + d = (this[i]>>(p-=k))&km; + if(p <= 0) { p += this._DB; --i; } + } + if(d > 0) m = true; + if(m) r += int2char(d); + } + } + return m?r:"0"; + } + + // (public) -this + function bnNegate() { var r = nbi(); BigInteger.ZERO._subTo(this,r); return r; } + + // (public) |this| + function bnAbs() { return (this.s<0)?this.negate():this; } + + // (public) return + if this > a, - if this < a, 0 if equal + function bnCompareTo(a) { + var r = this.s-a.s; + if(r) return r; + var i = this.t; + r = i-a.t; + if(r) return r; + while(--i >= 0) if((r = this[i] - a[i])) return r; + return 0; + } + + // returns bit length of the integer x + function nbits(x) { + var r = 1, t; + if((t=x>>>16)) { x = t; r += 16; } + if((t=x>>8)) { x = t; r += 8; } + if((t=x>>4)) { x = t; r += 4; } + if((t=x>>2)) { x = t; r += 2; } + if((t=x>>1)) { x = t; r += 1; } + return r; + } + + // (public) return the number of bits in "this" + function bnBitLength() { + if(this.t <= 0) return 0; + return this._DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this._DM)); + } + + // (protected) r = this << n*DB + function bnpDLShiftTo(n,r) { + var i; + for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; + for(i = n-1; i >= 0; --i) r[i] = 0; + r.t = this.t+n; + r.s = this.s; + } + + // (protected) r = this >> n*DB + function bnpDRShiftTo(n,r) { + for(var i = n; i < this.t; ++i) r[i-n] = this[i]; + r.t = Math.max(this.t-n,0); + r.s = this.s; + } + + // (protected) r = this << n + function bnpLShiftTo(n,r) { + var bs = n%this._DB; + var cbs = this._DB-bs; + var bm = (1<<cbs)-1; + var ds = Math.floor(n/this._DB), c = (this.s<<bs)&this._DM, i; + for(i = this.t-1; i >= 0; --i) { + r[i+ds+1] = (this[i]>>cbs)|c; + c = (this[i]&bm)<<bs; + } + for(i = ds-1; i >= 0; --i) r[i] = 0; + r[ds] = c; + r.t = this.t+ds+1; + r.s = this.s; + r._clamp(); + } + + // (protected) r = this >> n + function bnpRShiftTo(n,r) { + r.s = this.s; + var ds = Math.floor(n/this._DB); + if(ds >= this.t) { r.t = 0; return; } + var bs = n%this._DB; + var cbs = this._DB-bs; + var bm = (1<<bs)-1; + r[0] = this[ds]>>bs; + for(var i = ds+1; i < this.t; ++i) { + r[i-ds-1] |= (this[i]&bm)<<cbs; + r[i-ds] = this[i]>>bs; + } + if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs; + r.t = this.t-ds; + r._clamp(); + } + + // (protected) r = this - a + function bnpSubTo(a,r) { + var i = 0, c = 0, m = Math.min(a.t,this.t); + while(i < m) { + c += this[i]-a[i]; + r[i++] = c&this._DM; + c >>= this._DB; + } + if(a.t < this.t) { + c -= a.s; + while(i < this.t) { + c += this[i]; + r[i++] = c&this._DM; + c >>= this._DB; + } + c += this.s; + } + else { + c += this.s; + while(i < a.t) { + c -= a[i]; + r[i++] = c&this._DM; + c >>= this._DB; + } + c -= a.s; + } + r.s = (c<0)?-1:0; + if(c < -1) r[i++] = this._DV+c; + else if(c > 0) r[i++] = c; + r.t = i; + r._clamp(); + } + + // (protected) r = this * a, r != this,a (HAC 14.12) + // "this" should be the larger one if appropriate. + function bnpMultiplyTo(a,r) { + var x = this.abs(), y = a.abs(); + var i = x.t; + r.t = i+y.t; + while(--i >= 0) r[i] = 0; + for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); + r.s = 0; + r._clamp(); + if(this.s != a.s) BigInteger.ZERO._subTo(r,r); + } + + // (protected) r = this^2, r != this (HAC 14.16) + function bnpSquareTo(r) { + var x = this.abs(); + var i = r.t = 2*x.t; + while(--i >= 0) r[i] = 0; + for(i = 0; i < x.t-1; ++i) { + var c = x.am(i,x[i],r,2*i,0,1); + if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x._DV) { + r[i+x.t] -= x._DV; + r[i+x.t+1] = 1; + } + } + if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); + r.s = 0; + r._clamp(); + } + + // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) + // r != q, this != m. q or r may be null. + function bnpDivRemTo(m,q,r) { + var pm = m.abs(); + if(pm.t <= 0) return; + var pt = this.abs(); + if(pt.t < pm.t) { + if(q != null) q._fromInt(0); + if(r != null) this._copyTo(r); + return; + } + if(r == null) r = nbi(); + var y = nbi(), ts = this.s, ms = m.s; + var nsh = this._DB-nbits(pm[pm.t-1]); // normalize modulus + if(nsh > 0) { pm._lShiftTo(nsh,y); pt._lShiftTo(nsh,r); } + else { pm._copyTo(y); pt._copyTo(r); } + var ys = y.t; + var y0 = y[ys-1]; + if(y0 == 0) return; + var yt = y0*(1<<this._F1)+((ys>1)?y[ys-2]>>this._F2:0); + var d1 = this._FV/yt, d2 = (1<<this._F1)/yt, e = 1<<this._F2; + var i = r.t, j = i-ys, t = (q==null)?nbi():q; + y._dlShiftTo(j,t); + if(r.compareTo(t) >= 0) { + r[r.t++] = 1; + r._subTo(t,r); + } + BigInteger.ONE._dlShiftTo(ys,t); + t._subTo(y,y); // "negative" y so we can replace sub with am later + while(y.t < ys) y[y.t++] = 0; + while(--j >= 0) { + // Estimate quotient digit + var qd = (r[--i]==y0)?this._DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); + if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out + y._dlShiftTo(j,t); + r._subTo(t,r); + while(r[i] < --qd) r._subTo(t,r); + } + } + if(q != null) { + r._drShiftTo(ys,q); + if(ts != ms) BigInteger.ZERO._subTo(q,q); + } + r.t = ys; + r._clamp(); + if(nsh > 0) r._rShiftTo(nsh,r); // Denormalize remainder + if(ts < 0) BigInteger.ZERO._subTo(r,r); + } + + // (public) this mod a + function bnMod(a) { + var r = nbi(); + this.abs()._divRemTo(a,null,r); + if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a._subTo(r,r); + return r; + } + + // Modular reduction using "classic" algorithm + function Classic(m) { this.m = m; } + function cConvert(x) { + if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; + } + function cRevert(x) { return x; } + function cReduce(x) { x._divRemTo(this.m,null,x); } + function cMulTo(x,y,r) { x._multiplyTo(y,r); this.reduce(r); } + function cSqrTo(x,r) { x._squareTo(r); this.reduce(r); } + + dojo.extend(Classic, { + convert: cConvert, + revert: cRevert, + reduce: cReduce, + mulTo: cMulTo, + sqrTo: cSqrTo + }); + + // (protected) return "-1/this % 2^DB"; useful for Mont. reduction + // justification: + // xy == 1 (mod m) + // xy = 1+km + // xy(2-xy) = (1+km)(1-km) + // x[y(2-xy)] = 1-k^2m^2 + // x[y(2-xy)] == 1 (mod m^2) + // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 + // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. + // JS multiply "overflows" differently from C/C++, so care is needed here. + function bnpInvDigit() { + if(this.t < 1) return 0; + var x = this[0]; + if((x&1) == 0) return 0; + var y = x&3; // y == 1/x mod 2^2 + y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 + y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 + y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly; + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y*(2-x*y%this._DV))%this._DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return (y>0)?this._DV-y:-y; + } + + // Montgomery reduction + function Montgomery(m) { + this.m = m; + this.mp = m._invDigit(); + this.mpl = this.mp&0x7fff; + this.mph = this.mp>>15; + this.um = (1<<(m._DB-15))-1; + this.mt2 = 2*m.t; + } + + // xR mod m + function montConvert(x) { + var r = nbi(); + x.abs()._dlShiftTo(this.m.t,r); + r._divRemTo(this.m,null,r); + if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m._subTo(r,r); + return r; + } + + // x/R mod m + function montRevert(x) { + var r = nbi(); + x._copyTo(r); + this.reduce(r); + return r; + } + + // x = x/R mod m (HAC 14.32) + function montReduce(x) { + while(x.t <= this.mt2) // pad x so am has enough room later + x[x.t++] = 0; + for(var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x[i]*mp mod DV + var j = x[i]&0x7fff; + var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x._DM; + // use am to combine the multiply-shift-add into one call + j = i+this.m.t; + x[j] += this.m.am(0,u0,x,i,0,this.m.t); + // propagate carry + while(x[j] >= x._DV) { x[j] -= x._DV; x[++j]++; } + } + x._clamp(); + x._drShiftTo(this.m.t,x); + if(x.compareTo(this.m) >= 0) x._subTo(this.m,x); + } + + // r = "x^2/R mod m"; x != r + function montSqrTo(x,r) { x._squareTo(r); this.reduce(r); } + + // r = "xy/R mod m"; x,y != r + function montMulTo(x,y,r) { x._multiplyTo(y,r); this.reduce(r); } + + dojo.extend(Montgomery, { + convert: montConvert, + revert: montRevert, + reduce: montReduce, + mulTo: montMulTo, + sqrTo: montSqrTo + }); + + // (protected) true iff this is even + function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } + + // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) + function bnpExp(e,z) { + if(e > 0xffffffff || e < 1) return BigInteger.ONE; + var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; + g._copyTo(r); + while(--i >= 0) { + z.sqrTo(r,r2); + if((e&(1<<i)) > 0) z.mulTo(r2,g,r); + else { var t = r; r = r2; r2 = t; } + } + return z.revert(r); + } + + // (public) this^e % m, 0 <= e < 2^32 + function bnModPowInt(e,m) { + var z; + if(e < 256 || m._isEven()) z = new Classic(m); else z = new Montgomery(m); + return this._exp(e,z); + } + + dojo.extend(BigInteger, { + // protected, not part of the official API + _DB: dbits, + _DM: (1 << dbits) - 1, + _DV: 1 << dbits, + + _FV: Math.pow(2, BI_FP), + _F1: BI_FP - dbits, + _F2: 2 * dbits-BI_FP, + + // protected + _copyTo: bnpCopyTo, + _fromInt: bnpFromInt, + _fromString: bnpFromString, + _clamp: bnpClamp, + _dlShiftTo: bnpDLShiftTo, + _drShiftTo: bnpDRShiftTo, + _lShiftTo: bnpLShiftTo, + _rShiftTo: bnpRShiftTo, + _subTo: bnpSubTo, + _multiplyTo: bnpMultiplyTo, + _squareTo: bnpSquareTo, + _divRemTo: bnpDivRemTo, + _invDigit: bnpInvDigit, + _isEven: bnpIsEven, + _exp: bnpExp, + + // public + toString: bnToString, + negate: bnNegate, + abs: bnAbs, + compareTo: bnCompareTo, + bitLength: bnBitLength, + mod: bnMod, + modPowInt: bnModPowInt + }); + + dojo._mixin(BigInteger, { + // "constants" + ZERO: nbv(0), + ONE: nbv(1), + + // internal functions + _nbi: nbi, + _nbv: nbv, + _nbits: nbits, + + // internal classes + _Montgomery: Montgomery + }); + + // export to DojoX + dojox.math.BigInteger = BigInteger; + + return dojox.math.BigInteger; +}); diff --git a/js/dojo/dojox/math/README b/js/dojo/dojox/math/README new file mode 100644 index 0000000..27d29ff --- /dev/null +++ b/js/dojo/dojox/math/README @@ -0,0 +1,40 @@ +------------------------------------------------------------------------------- +DojoX Math +------------------------------------------------------------------------------- +Version 0.9 +Release date: 10/20/2007 +------------------------------------------------------------------------------- +Project state: +experimental +------------------------------------------------------------------------------- +Credits + Cal Henderson + Dan Pupius + Tom Trenka (ttrenka AT gmail.com) + Eugene Lazutkin (eugene.lazutkin AT gmail.com) +------------------------------------------------------------------------------- +Project description + +A port of the main functionality of dojo.math 0.4. Includes advanced math +functions, abstract curve definitions, and some point calculations. + +------------------------------------------------------------------------------- +Dependencies: + +Depends on the Dojo Core, v1.0 +------------------------------------------------------------------------------- +Documentation + +See the API documentation. +------------------------------------------------------------------------------- +Installation instructions + +Grab the following from the Dojo SVN Repository: +http://svn.dojotoolkit.org/src/dojox/trunk/math.js +http://svn.dojotoolkit.org/src/dojox/trunk/math/* + +Install into the following directory structure: +/dojox/math/ + +...which should be at the same level as your Dojo checkout. +------------------------------------------------------------------------------- diff --git a/js/dojo/dojox/math/_base.js b/js/dojo/dojox/math/_base.js new file mode 100644 index 0000000..dc19c66 --- /dev/null +++ b/js/dojo/dojox/math/_base.js @@ -0,0 +1,163 @@ +//>>built +// AMD-ID "dojox/math/_base" +define("dojox/math/_base", ["dojo", "dojox"], function(dojo, dojox) { + dojo.getObject("math", true, dojox); + + var m = dojox.math; + dojo.mixin(dojox.math, { + toRadians: function(/* Number */n){ + // summary: + // Convert the passed number to radians. + return (n*Math.PI)/180; // Number + }, + toDegrees: function(/* Number */n){ + // summary: + // Convert the passed number to degrees. + return (n*180)/Math.PI; // Number + }, + degreesToRadians: function(/* Number */n){ + // summary: + // Deprecated. Use dojox.math.toRadians. + return m.toRadians(n); // Number + }, + radiansToDegrees: function(/* Number */n){ + // summary: + // Deprecated. Use dojox.math.toDegrees. + return m.toDegrees(n); // Number + }, + + _gamma: function(z){ + // summary: + // Compute the gamma function for the passed number. + // Approximately 14 dijits of precision with non-integers. + var answer = 1; // 0! + // gamma(n+1) = n * gamma(n) + while (--z >= 1){ + answer *= z; + } + if(z == 0){ return answer; } // normal integer quick return + if(Math.floor(z) == z){ return NaN; } // undefined at nonpositive integers since sin() below will return 0 + // assert: z < 1, remember this z is really z-1 + if(z == -0.5){ return Math.sqrt(Math.PI); } // popular gamma(1/2) + if(z < -0.5){ // remember this z is really z-1 + return Math.PI / (Math.sin(Math.PI * (z + 1)) * this._gamma(-z)); // reflection + } + // assert: -0.5 < z < 1 + // Spouge approximation algorithm + var a = 13; + // c[0] = sqrt(2*PI) / exp(a) + // var kfact = 1 + // for (var k=1; k < a; k++){ + // c[k] = pow(-k + a, k - 0.5) * exp(-k) / kfact + // kfact *= -k // (-1)^(k-1) * (k-1)! + // } + var c = [ // precomputed from the above algorithm + 5.6658056015186327e-6, + 1.2743717663379679, + -4.9374199093155115, + 7.8720267032485961, + -6.6760503749436087, + 3.2525298444485167, + -9.1852521441026269e-1, + 1.4474022977730785e-1, + -1.1627561382389853e-2, + 4.0117980757066622e-4, + -4.2652458386405744e-6, + 6.6651913290336086e-9, + -1.5392547381874824e-13 + ]; + var sum = c[0]; + for (var k=1; k < a; k++){ + sum += c[k] / (z + k); + } + return answer * Math.pow(z + a, z + 0.5) / Math.exp(z) * sum; + }, + + factorial: function(/* Number */n){ + // summary: + // Return the factorial of n + return this._gamma(n+1); // Number + }, + + permutations: function(/* Number */n, /* Number */k){ + // summary: + // TODO + if(n==0 || k==0){ + return 1; // Number + } + return this.factorial(n) / this.factorial(n-k); + }, + + combinations: function(/* Number */n, /* Number */r){ + // summary: + // TODO + if(n==0 || r==0){ + return 1; // Number + } + return this.factorial(n) / (this.factorial(n-r) * this.factorial(r)); // Number + }, + + bernstein: function(/* Number */t, /* Number */n, /* Number */ i){ + // summary: + // TODO + return this.combinations(n, i) * Math.pow(t, i) * Math.pow(1-t, n-i); // Number + }, + + gaussian: function(){ + // summary: + // Return a random number based on the Gaussian algo. + var k=2; + do{ + var i=2*Math.random()-1; + var j=2*Math.random()-1; + k = i*i+j*j; + }while(k>=1); + return i * Math.sqrt((-2*Math.log(k))/k); // Number + }, + + // create a range of numbers + range: function(/* Number */a, /* Number? */b, /* Number? */step){ + // summary: + // Create a range of numbers based on the parameters. + if(arguments.length<2){ + b=a,a=0; + } + var range=[], s=step||1, i; + if(s>0){ + for(i=a; i<b; i+=s){ + range.push(i); + } + }else{ + if(s<0){ + for(i=a; i>b; i+=s){ + range.push(i); + } + }else{ + throw new Error("dojox.math.range: step must not be zero."); + } + } + return range; // Array + }, + + distance: function(/* Array */a, /* Array */b){ + // summary: + // Calculate the distance between point A and point B + return Math.sqrt(Math.pow(b[0]-a[0],2)+Math.pow(b[1]-a[1],2)); // Number + }, + + midpoint: function(/* Array */a, /* Array */b){ + // summary: + // Calculate the midpoint between points A and B. A and B may be multidimensional. + if(a.length!=b.length){ + console.error("dojox.math.midpoint: Points A and B are not the same dimensionally.", a, b); + } + var m=[]; + for(var i=0; i<a.length; i++){ + m[i]=(a[i]+b[i])/2; + } + return m; // Array + } + }); + + return dojox.math; +}); diff --git a/js/dojo/dojox/math/curves.js b/js/dojo/dojox/math/curves.js new file mode 100644 index 0000000..c549b8c --- /dev/null +++ b/js/dojo/dojox/math/curves.js @@ -0,0 +1,195 @@ +//>>built +// AMD-ID "dojox/math/curves" +define("dojox/math/curves", ["dojo", "dojox"], function(dojo, dojox) { +dojo.getObject("math.curves", true, dojox); + +dojo.mixin(dojox.math.curves, { + Line:function (start, end) { + this.start = start; + this.end = end; + this.dimensions = start.length; + for (var i = 0; i < start.length; i++) { + start[i] = Number(start[i]); + } + for (var i = 0; i < end.length; i++) { + end[i] = Number(end[i]); + } + this.getValue = function (n) { + var retVal = new Array(this.dimensions); + for (var i = 0; i < this.dimensions; i++) { + retVal[i] = ((this.end[i] - this.start[i]) * n) + this.start[i]; + } + return retVal; + }; + return this; + }, + Bezier:function(pnts) { + this.getValue = function (step) { + if (step >= 1) { + return this.p[this.p.length - 1]; + } + if (step <= 0) { + return this.p[0]; + } + var retVal = new Array(this.p[0].length); + for (var k = 0; j < this.p[0].length; k++) { + retVal[k] = 0; + } + for (var j = 0; j < this.p[0].length; j++) { + var C = 0; + var D = 0; + for (var i = 0; i < this.p.length; i++) { + C += this.p[i][j] * this.p[this.p.length - 1][0] * dojox.math.bernstein(step, this.p.length, i); + } + for (var l = 0; l < this.p.length; l++) { + D += this.p[this.p.length - 1][0] * dojox.math.bernstein(step, this.p.length, l); + } + retVal[j] = C / D; + } + return retVal; + }; + this.p = pnts; + return this; + }, + CatmullRom:function (pnts, c) { + this.getValue = function (step) { + var percent = step * (this.p.length - 1); + var node = Math.floor(percent); + var progress = percent - node; + var i0 = node - 1; + if (i0 < 0) { + i0 = 0; + } + var i = node; + var i1 = node + 1; + if (i1 >= this.p.length) { + i1 = this.p.length - 1; + } + var i2 = node + 2; + if (i2 >= this.p.length) { + i2 = this.p.length - 1; + } + var u = progress; + var u2 = progress * progress; + var u3 = progress * progress * progress; + var retVal = new Array(this.p[0].length); + for (var k = 0; k < this.p[0].length; k++) { + var x1 = (-this.c * this.p[i0][k]) + ((2 - this.c) * this.p[i][k]) + ((this.c - 2) * this.p[i1][k]) + (this.c * this.p[i2][k]); + var x2 = (2 * this.c * this.p[i0][k]) + ((this.c - 3) * this.p[i][k]) + ((3 - 2 * this.c) * this.p[i1][k]) + (-this.c * this.p[i2][k]); + var x3 = (-this.c * this.p[i0][k]) + (this.c * this.p[i1][k]); + var x4 = this.p[i][k]; + retVal[k] = x1 * u3 + x2 * u2 + x3 * u + x4; + } + return retVal; + }; + if (!c) { + this.c = 0.7; + } else { + this.c = c; + } + this.p = pnts; + return this; + }, + Arc:function (start, end, ccw){ + function translate(a,b){ + var c=new Array(a.length); + for(var i=0; i<a.length; i++){ c[i]=a[i]+b[i]; } + return c; + } + function invert(a){ + var b = new Array(a.length); + for(var i=0; i<a.length; i++){ b[i]=-a[i]; } + return b; + } + var center = dojox.math.midpoint(start, end); + var sides = translate(invert(center), start); + var rad = Math.sqrt(Math.pow(sides[0], 2) + Math.pow(sides[1], 2)); + var theta = dojox.math.radiansToDegrees(Math.atan(sides[1] / sides[0])); + if (sides[0] < 0){ + theta -= 90; + } else { + theta += 90; + } + dojox.math.curves.CenteredArc.call(this, center, rad, theta, theta + (ccw ? -180 : 180)); + }, + CenteredArc:function (center, radius, start, end) { + this.center = center; + this.radius = radius; + this.start = start || 0; + this.end = end; + this.getValue = function (n) { + var retVal = new Array(2); + var theta = dojox.math.degreesToRadians(this.start + ((this.end - this.start) * n)); + retVal[0] = this.center[0] + this.radius * Math.sin(theta); + retVal[1] = this.center[1] - this.radius * Math.cos(theta); + return retVal; + }; + return this; + }, + Circle:function(center, radius){ + dojox.math.curves.CenteredArc.call(this, center, radius, 0, 360); + return this; + }, + Path:function () { + var curves = []; + var weights = []; + var ranges = []; + var totalWeight = 0; + this.add = function (curve, weight) { + if (weight < 0) { + console.error("dojox.math.curves.Path.add: weight cannot be less than 0"); + } + curves.push(curve); + weights.push(weight); + totalWeight += weight; + computeRanges(); + }; + this.remove = function (curve) { + for (var i = 0; i < curves.length; i++) { + if (curves[i] == curve) { + curves.splice(i, 1); + totalWeight -= weights.splice(i, 1)[0]; + break; + } + } + computeRanges(); + }; + this.removeAll = function () { + curves = []; + weights = []; + totalWeight = 0; + }; + this.getValue = function (n) { + var found = false, value = 0; + for (var i = 0; i < ranges.length; i++) { + var r = ranges[i]; + if (n >= r[0] && n < r[1]) { + var subN = (n - r[0]) / r[2]; + value = curves[i].getValue(subN); + found = true; + break; + } + } + if (!found) { + value = curves[curves.length - 1].getValue(1); + } + for (var j = 0; j < i; j++) { + value = dojox.math.points.translate(value, curves[j].getValue(1)); + } + return value; + }; + function computeRanges() { + var start = 0; + for (var i = 0; i < weights.length; i++) { + var end = start + weights[i] / totalWeight; + var len = end - start; + ranges[i] = [start, end, len]; + start = end; + } + } + return this; + } +}); + +return dojox.math.curves; +}); diff --git a/js/dojo/dojox/math/matrix.js b/js/dojo/dojox/math/matrix.js new file mode 100644 index 0000000..4470149 --- /dev/null +++ b/js/dojo/dojox/math/matrix.js @@ -0,0 +1,296 @@ +//>>built +// AMD-ID "dojox/math/matrix" +define("dojox/math/matrix", ["dojo", "dojox"], function(dojo, dojox) { +dojo.getObject("math.matrix", true, dojox); + +dojo.mixin(dojox.math.matrix, { + iDF:0, + ALMOST_ZERO: 1e-10, + multiply: function(/* Array */a, /* Array */b){ + // summary + // Multiply matrix a by matrix b. + var ay=a.length, ax=a[0].length, by=b.length, bx=b[0].length; + if(ax!=by){ + console.warn("Can't multiply matricies of sizes " + ax + "," + ay + " and " + bx + "," + by); + return [[0]]; + } + var c=[]; + for (var k=0; k<ay; k++) { + c[k]=[]; + for(var i=0; i<bx; i++){ + c[k][i]=0; + for(var m=0; m<ax; m++){ + c[k][i]+=a[k][m]*b[m][i]; + } + } + } + return c; // Array + }, + product: function(/* Array... */){ + // summary + // Return the product of N matrices + if (arguments.length==0){ + console.warn("can't multiply 0 matrices!"); + return 1; + } + var m=arguments[0]; + for(var i=1; i<arguments.length; i++){ + m=this.multiply(m, arguments[i]); + } + return m; // Array + }, + sum: function(/* Array... */){ + // summary + // Return the sum of N matrices + if(arguments.length==0){ + console.warn("can't sum 0 matrices!"); + return 0; // Number + } + var m=this.copy(arguments[0]); + var rows=m.length; + if(rows==0){ + console.warn("can't deal with matrices of 0 rows!"); + return 0; + } + var cols=m[0].length; + if(cols==0){ + console.warn("can't deal with matrices of 0 cols!"); + return 0; + } + for(var i=1; i<arguments.length; ++i){ + var arg=arguments[i]; + if(arg.length!=rows || arg[0].length!=cols){ + console.warn("can't add matrices of different dimensions: first dimensions were " + rows + "x" + cols + ", current dimensions are " + arg.length + "x" + arg[0].length); + return 0; + } + for(var r=0; r<rows; r++) { + for(var c=0; c<cols; c++) { + m[r][c]+=arg[r][c]; + } + } + } + return m; // Array + }, + inverse: function(/* Array */a){ + // summary + // Return the inversion of the passed matrix + if(a.length==1 && a[0].length==1){ + return [[1/a[0][0]]]; // Array + } + var tms=a.length, m=this.create(tms, tms), mm=this.adjoint(a), det=this.determinant(a), dd=0; + if(det==0){ + console.warn("Determinant Equals 0, Not Invertible."); + return [[0]]; + }else{ + dd=1/det; + } + for(var i=0; i<tms; i++) { + for (var j=0; j<tms; j++) { + m[i][j]=dd*mm[i][j]; + } + } + return m; // Array + }, + determinant: function(/* Array */a){ + // summary + // Calculate the determinant of the passed square matrix. + if(a.length!=a[0].length){ + console.warn("Can't calculate the determinant of a non-squre matrix!"); + return 0; + } + var tms=a.length, det=1, b=this.upperTriangle(a); + for (var i=0; i<tms; i++){ + var bii=b[i][i]; + if (Math.abs(bii)<this.ALMOST_ZERO) { + return 0; // Number + } + det*=bii; + } + det*=this.iDF; + return det; // Number + }, + upperTriangle: function(/* Array */m){ + // Summary + // Find the upper triangle of the passed matrix and return it. + m=this.copy(m); + var f1=0, temp=0, tms=m.length, v=1; + this.iDF=1; + for(var col=0; col<tms-1; col++){ + if(typeof m[col][col]!="number") { + console.warn("non-numeric entry found in a numeric matrix: m[" + col + "][" + col + "]=" + m[col][col]); + } + v=1; + var stop_loop=0; + while((m[col][col] == 0) && !stop_loop){ + if (col+v>=tms){ + this.iDF=0; + stop_loop=1; + }else{ + for(var r=0; r<tms; r++){ + temp=m[col][r]; + m[col][r]=m[col+v][r]; + m[col+v][r]=temp; + } + v++; + this.iDF*=-1; + } + } + for(var row=col+1; row<tms; row++){ + if(typeof m[row][col]!="number"){ + console.warn("non-numeric entry found in a numeric matrix: m[" + row + "][" + col + "]=" + m[row][col]); + } + if(typeof m[col][row]!="number"){ + console.warn("non-numeric entry found in a numeric matrix: m[" + col + "][" + row + "]=" + m[col][row]); + } + if(m[col][col]!=0){ + var f1=(-1)* m[row][col]/m[col][col]; + for (var i=col; i<tms; i++){ + m[row][i]=f1*m[col][i]+m[row][i]; + } + } + } + } + return m; // Array + }, + create: function(/* Number */a, /* Number */b, /* Number? */value){ + // summary + // Create a new matrix with rows a and cols b, and pre-populate with value. + value=value||0; + var m=[]; + for (var i=0; i<b; i++){ + m[i]=[]; + for(var j=0; j<a; j++) { + m[i][j]=value; + } + } + return m; // Array + }, + ones: function(/* Number */a, /* Number */b){ + // summary + // Create a matrix pre-populated with ones + return this.create(a, b, 1); // Array + }, + zeros: function(/* Number */a, /* Number */b){ + // summary + // Create a matrix pre-populated with zeros + return this.create(a, b); // Array + }, + identity: function(/* Number */size, /* Number? */scale){ + // summary + // Create an identity matrix based on the size and scale. + scale=scale||1; + var m=[]; + for(var i=0; i<size; i++){ + m[i]=[]; + for(var j=0; j<size; j++){ + m[i][j]=(i==j?scale:0); + } + } + return m; // Array + }, + adjoint: function(/* Array */a){ + // summary + // Find the adjoint of the passed matrix + var tms=a.length; + if(tms<=1){ + console.warn("Can't find the adjoint of a matrix with a dimension less than 2"); + return [[0]]; + } + if(a.length!=a[0].length){ + console.warn("Can't find the adjoint of a non-square matrix"); + return [[0]]; + } + var m=this.create(tms, tms), ap=this.create(tms-1, tms-1); + var ii=0, jj=0, ia=0, ja=0, det=0; + for(var i=0; i<tms; i++){ + for (var j=0; j<tms; j++){ + ia=0; + for(ii=0; ii<tms; ii++){ + if(ii==i){ + continue; + } + ja = 0; + for(jj=0; jj<tms; jj++){ + if(jj==j){ + continue; + } + ap[ia][ja] = a[ii][jj]; + ja++; + } + ia++; + } + det=this.determinant(ap); + m[i][j]=Math.pow(-1, (i+j))*det; + } + } + return this.transpose(m); // Array + }, + transpose: function(/* Array */a){ + // summary + // Transpose the passed matrix (i.e. rows to columns) + var m=this.create(a.length, a[0].length); + for(var i=0; i<a.length; i++){ + for(var j=0; j<a[i].length; j++){ + m[j][i]=a[i][j]; + } + } + return m; // Array + }, + format: function(/* Array */a, /* Number? */points){ + // summary + // Return a string representation of the matrix, rounded to points (if needed) + points=points||5; + function format_int(x, dp){ + var fac=Math.pow(10, dp); + var a=Math.round(x*fac)/fac; + var b=a.toString(); + if(b.charAt(0)!="-"){ + b=" "+b; + } + if(b.indexOf(".")>-1){ + b+="."; + } + while(b.length<dp+3){ + b+="0"; + } + return b; + } + var ya=a.length; + var xa=ya>0?a[0].length:0; + var buffer=""; + for(var y=0; y<ya; y++){ + buffer+="| "; + for(var x=0; x<xa; x++){ + buffer+=format_int(a[y][x], points)+" "; + } + buffer+="|\n"; + } + return buffer; // string + }, + copy: function(/* Array */a){ + // summary + // Create a copy of the passed matrix + var ya=a.length, xa=a[0].length, m=this.create(xa, ya); + for(var y=0; y<ya; y++){ + for(var x=0; x<xa; x++){ + m[y][x]=a[y][x]; + } + } + return m; // Array + }, + scale: function(/* Array */a, /* Number */factor){ + // summary + // Create a copy of passed matrix and scale each member by factor. + a=this.copy(a); + var ya=a.length, xa=a[0].length; + for(var y=0; y<ya; y++){ + for(var x=0; x<xa; x++){ + a[y][x]*=factor; + } + } + return a; + } +}); + +return dojox.math.matrix; +}); diff --git a/js/dojo/dojox/math/random/Secure.js b/js/dojo/dojox/math/random/Secure.js new file mode 100644 index 0000000..01a08bd --- /dev/null +++ b/js/dojo/dojox/math/random/Secure.js @@ -0,0 +1,99 @@ +//>>built +// AMD-ID "dojox/math/random/Secure" +define("dojox/math/random/Secure", ["dojo"], function(dojo) { + +// Copyright (c) 2005 Tom Wu +// All Rights Reserved. +// See "LICENSE-BigInteger" for details. + +// Random number generator - requires a PRNG backend, e.g. prng4.js + +dojo.declare("dojox.math.random.Secure", null, { + // summary: + // Super simple implementation of a random number generator, + // which relies on Math.random(). + + constructor: function(prng, noEvents){ + // summary: + // Intializes an instance of a secure random generator. + // prng: Function: + // function that returns an instance of PRNG (pseudorandom number generator) + // with two methods: init(array) and next(). It should have a property "size" + // to indicate the required pool size. + // noEvents: Boolean?: + // if false or absent, onclick and onkeypress event will be used to add + // "randomness", otherwise events will not be used. + this.prng = prng; + + // Initialize the pool with junk if needed. + var p = this.pool = new Array(prng.size); + this.pptr = 0; + for(var i = 0, len = prng.size; i < len;) { // extract some randomness from Math.random() + var t = Math.floor(65536 * Math.random()); + p[i++] = t >>> 8; + p[i++] = t & 255; + } + this.seedTime(); + + if(!noEvents){ + this.h = [ + dojo.connect(dojo.body(), "onclick", this, "seedTime"), + dojo.connect(dojo.body(), "onkeypress", this, "seedTime") + ]; + } + }, + + destroy: function(){ + // summary: + // Disconnects events, if any, preparing the object for GC. + if(this.h){ + dojo.forEach(this.h, dojo.disconnect); + } + }, + + nextBytes: function(/* Array */ byteArray){ + // summary: + // Fills in an array of bytes with random numbers + // byteArray: Array: + // array to be filled in with random numbers, only existing + // elements will be filled. + + var state = this.state; + + if(!state){ + this.seedTime(); + state = this.state = this.prng(); + state.init(this.pool); + for(var p = this.pool, i = 0, len = p.length; i < len; p[i++] = 0); + this.pptr = 0; + //this.pool = null; + } + + for(var i = 0, len = byteArray.length; i < len; ++i){ + byteArray[i] = state.next(); + } + }, + + seedTime: function() { + // summary: + // Mix in the current time (w/milliseconds) into the pool + this._seed_int(new Date().getTime()); + }, + + _seed_int: function(x) { + // summary: + // Mix in a 32-bit integer into the pool + var p = this.pool, i = this.pptr; + p[i++] ^= x & 255; + p[i++] ^= (x >> 8) & 255; + p[i++] ^= (x >> 16) & 255; + p[i++] ^= (x >> 24) & 255; + if(i >= this.prng.size){ + i -= this.prng.size; + } + this.pptr = i; + } +}); + +return dojox.math.random.Secure; +}); diff --git a/js/dojo/dojox/math/random/Simple.js b/js/dojo/dojox/math/random/Simple.js new file mode 100644 index 0000000..0061979 --- /dev/null +++ b/js/dojo/dojox/math/random/Simple.js @@ -0,0 +1,25 @@ +//>>built +define("dojox/math/random/Simple", ["dojo"], function(dojo) { + + return dojo.declare("dojox.math.random.Simple", null, { + // summary: + // Super simple implementation of a random number generator, + // which relies on Math.random(). + + destroy: function(){ + // summary: + // Prepares the object for GC. (empty in this case) + }, + + nextBytes: function(/* Array */ byteArray){ + // summary: + // Fills in an array of bytes with random numbers + // byteArray: Array: + // array to be filled in with random numbers, only existing + // elements will be filled. + for(var i = 0, l = byteArray.length; i < l; ++i){ + byteArray[i] = Math.floor(256 * Math.random()); + } + } + }); +}); diff --git a/js/dojo/dojox/math/random/prng4.js b/js/dojo/dojox/math/random/prng4.js new file mode 100644 index 0000000..1d08b4d --- /dev/null +++ b/js/dojo/dojox/math/random/prng4.js @@ -0,0 +1,60 @@ +//>>built +// AMD-ID "dojox/math/random/prng4" +define("dojox/math/random/prng4", ["dojo", "dojox"], function(dojo, dojox) { + + dojo.getObject("math.random.prng4", true, dojox); + +// Copyright (c) 2005 Tom Wu +// All Rights Reserved. +// See "LICENSE-BigInteger" for details. + + // prng4.js - uses Arcfour as a PRNG + + function Arcfour() { + this.i = 0; + this.j = 0; + this.S = new Array(256); + } + + dojo.extend(Arcfour, { + init: function(key){ + // summary: + // Initialize arcfour context + // key: Array: + // an array of ints, each from [0..255] + var i, j, t, S = this.S, len = key.length; + for(i = 0; i < 256; ++i){ + S[i] = i; + } + j = 0; + for(i = 0; i < 256; ++i){ + j = (j + S[i] + key[i % len]) & 255; + t = S[i]; + S[i] = S[j]; + S[j] = t; + } + this.i = 0; + this.j = 0; + }, + + next: function(){ + var t, i, j, S = this.S; + this.i = i = (this.i + 1) & 255; + this.j = j = (this.j + S[i]) & 255; + t = S[i]; + S[i] = S[j]; + S[j] = t; + return S[(t + S[i]) & 255]; + } + }); + + dojox.math.random.prng4 = function(){ + return new Arcfour(); + }; + + // Pool size must be a multiple of 4 and greater than 32. + // An array of bytes the size of the pool will be passed to init() + dojox.math.random.prng4.size = 256; + + return dojox.math.random.prng4; +}); diff --git a/js/dojo/dojox/math/round.js b/js/dojo/dojox/math/round.js new file mode 100644 index 0000000..84e2c13 --- /dev/null +++ b/js/dojo/dojox/math/round.js @@ -0,0 +1,66 @@ +//>>built +// AMD-ID "dojox/math/round" +define("dojox/math/round", ["dojo", "dojox"], function(dojo, dojox) { + + dojo.getObject("math.round", true, dojox); + dojo.experimental("dojox.math.round"); + + dojox.math.round = function(/*Number*/value, /*Number?*/places, /*Number?*/increment){ + // summary: + // Similar to dojo.number.round, but compensates for binary floating point artifacts + // description: + // Rounds to the nearest value with the given number of decimal places, away from zero if equal, + // similar to Number.toFixed(). Rounding can be done by fractional increments also. + // Makes minor adjustments to accommodate for precision errors due to binary floating point representation + // of Javascript Numbers. See http://speleotrove.com/decimal/decifaq.html for more information. + // Because of this adjustment, the rounding may not be mathematically correct for full precision + // floating point values. The calculations assume 14 significant figures, so the accuracy will + // be limited to a certain number of decimal places preserved will vary with the magnitude of + // the input. This is not a substitute for decimal arithmetic. + // value: + // The number to round + // places: + // The number of decimal places where rounding takes place. Defaults to 0 for whole rounding. + // Must be non-negative. + // increment: + // Rounds next place to nearest value of increment/10. 10 by default. + // example: + // >>> 4.8-(1.1+2.2) + // 1.4999999999999996 + // >>> Math.round(4.8-(1.1+2.2)) + // 1 + // >>> dojox.math.round(4.8-(1.1+2.2)) + // 2 + // >>> ((4.8-(1.1+2.2))/100) + // 0.014999999999999996 + // >>> ((4.8-(1.1+2.2))/100).toFixed(2) + // "0.01" + // >>> dojox.math.round((4.8-(1.1+2.2))/100,2) + // 0.02 + // >>> dojox.math.round(10.71, 0, 2.5) + // 10.75 + // >>> dojo.number.round(162.295, 2) + // 162.29 + // >>> dojox.math.round(162.295, 2) + // 162.3 + var wholeFigs = Math.log(Math.abs(value))/Math.log(10); + var factor = 10 / (increment || 10); + var delta = Math.pow(10, -15 + wholeFigs); + return (factor * (+value + (value > 0 ? delta : -delta))).toFixed(places) / factor; // Number + } + + if((0.9).toFixed() == 0){ + // (isIE) toFixed() bug workaround: Rounding fails on IE when most significant digit + // is just after the rounding place and is >=5 + var round = dojox.math.round; + dojox.math.round = function(v, p, m){ + var d = Math.pow(10, -p || 0), a = Math.abs(v); + if(!v || a >= d || a * Math.pow(10, p + 1) < 5){ + d = 0; + } + return round(v, p, m) + (v > 0 ? d : -d); + } + } + + return dojox.math.round; +}); diff --git a/js/dojo/dojox/math/stats.js b/js/dojo/dojox/math/stats.js new file mode 100644 index 0000000..ddb756b --- /dev/null +++ b/js/dojo/dojox/math/stats.js @@ -0,0 +1,195 @@ +//>>built +// AMD-ID "dojox/math/stats" +define("dojox/math/stats", ["dojo", "../main"], function(dojo, dojox) { + + dojo.getObject("math.stats", true, dojox); + + var st = dojox.math.stats; + dojo.mixin(st, { + sd: function(/* Number[] */a){ + // summary: + // Returns the standard deviation of the passed arguments. + return Math.sqrt(st.variance(a)); // Number + }, + + variance: function(/* Number[] */a){ + // summary: + // Find the variance in the passed array of numbers. + var mean=0, squares=0; + dojo.forEach(a, function(item){ + mean+=item; + squares+=Math.pow(item,2); + }); + return (squares/a.length)-Math.pow(mean/a.length, 2); // Number + }, + + bestFit: function(/* Object[] || Number[] */a, /* String? */xProp, /* String? */yProp){ + // summary: + // Calculate the slope and intercept in a linear fashion. An array + // of objects is expected; optionally you can pass in the property + // names for "x" and "y", else x/y is used as the default. If you + // pass an array of numbers, it will be mapped to a set of {x,y} objects + // where x = the array index. + xProp = xProp || "x", yProp = yProp || "y"; + if(a[0] !== undefined && typeof(a[0]) == "number"){ + // this is an array of numbers, so use the index as x. + a = dojo.map(a, function(item, idx){ + return { x: idx, y: item }; + }); + } + + var sx = 0, sy = 0, sxx = 0, syy = 0, sxy = 0, stt = 0, sts = 0, n = a.length, t; + for(var i=0; i<n; i++){ + sx += a[i][xProp]; + sy += a[i][yProp]; + sxx += Math.pow(a[i][xProp], 2); + syy += Math.pow(a[i][yProp], 2); + sxy += a[i][xProp] * a[i][yProp]; + } + + // we use the following because it's more efficient and accurate for determining the slope. + for(i=0; i<n; i++){ + t = a[i][xProp] - sx/n; + stt += t*t; + sts += t*a[i][yProp]; + } + var slope = sts/(stt||1); // prevent divide by zero. + + // get Pearson's R + var d = Math.sqrt((sxx - Math.pow(sx,2)/n) * (syy - Math.pow(sy,2)/n)); + if(d === 0){ + throw new Error("dojox.math.stats.bestFit: the denominator for Pearson's R is 0."); + } + + var r = (sxy-(sx*sy/n)) / d; + var r2 = Math.pow(r, 2); + if(slope < 0){ + r = -r; + } + + // to use: y = slope*x + intercept; + return { // Object + slope: slope, + intercept: (sy - sx*slope)/(n||1), + r: r, + r2: r2 + }; + }, + + forecast: function(/* Object[] || Number[] */a, /* Number */x, /* String? */xProp, /* String? */yProp){ + // summary: + // Using the bestFit algorithm above, find y for the given x. + var fit = st.bestFit(a, xProp, yProp); + return (fit.slope * x) + fit.intercept; // Number + }, + + mean: function(/* Number[] */a){ + // summary: + // Returns the mean value in the passed array. + var t=0; + dojo.forEach(a, function(v){ + t += v; + }); + return t / Math.max(a.length, 1); // Number + }, + + min: function(/* Number[] */a){ + // summary: + // Returns the min value in the passed array. + return Math.min.apply(null, a); // Number + }, + + max: function(/* Number[] */a){ + // summary: + // Returns the max value in the passed array. + return Math.max.apply(null, a); // Number + }, + + median: function(/* Number[] */a){ + // summary: + // Returns the value closest to the middle from a sorted version of the passed array. + var t = a.slice(0).sort(function(a, b){ return a - b; }); + return (t[Math.floor(a.length/2)] + t[Math.ceil(a.length/2)])/2; // Number + }, + + mode: function(/* Number[] */a){ + // summary: + // Returns the mode from the passed array (number that appears the most often). + // This is not the most efficient method, since it requires a double scan, but + // is ensures accuracy. + var o = {}, r = 0, m = Number.MIN_VALUE; + dojo.forEach(a, function(v){ + (o[v]!==undefined)?o[v]++:o[v]=1; + }); + + // we did the lookup map because we need the number that appears the most. + for(var p in o){ + if(m < o[p]){ + m = o[p], r = p; + } + } + return r; // Number + }, + + sum: function(/* Number[] */a){ + // summary: + // Return the sum of all the numbers in the passed array. Does + // not check to make sure values within a are NaN (should simply + // return NaN). + var sum = 0; + dojo.forEach(a, function(n){ + sum += n; + }); + return sum; // Number + }, + + approxLin: function(a, pos){ + // summary: + // Returns a linearly approximated value from an array using + // a normalized float position value. + // a: Number[]: + // a sorted numeric array to be used for the approximation. + // pos: Number: + // a position number from 0 to 1. If outside of this range it + // will be clamped. + // returns: Number + var p = pos * (a.length - 1), t = Math.ceil(p), f = t - 1; + if(f < 0){ return a[0]; } + if(t >= a.length){ return a[a.length - 1]; } + return a[f] * (t - p) + a[t] * (p - f); // Number + }, + + summary: function(a, alreadySorted){ + // summary: + // Returns a non-parametric collection of summary statistics: + // the classic five-number summary extended to the Bowley's + // seven-figure summary. + // a: Number[]: + // a numeric array to be appraised. + // alreadySorted: Boolean?: + // a Boolean flag to indicated that the array is already sorted. + // This is an optional flag purely to improve the performance. + // If skipped, the array will be assumed unsorted. + // returns: Object + if(!alreadySorted){ + a = a.slice(0); // copy the array + a.sort(function(a, b){ return a - b; }); // sort it properly + } + var l = st.approxLin, + result = { + // the five-number summary + min: a[0], // minimum + p25: l(a, 0.25), // lower quartile + med: l(a, 0.5), // median + p75: l(a, 0.75), // upper quartile + max: a[a.length - 1], // maximum + // extended to the Bowley's seven-figure summary + p10: l(a, 0.1), // first decile + p90: l(a, 0.9) // last decile + }; + return result; // Object + } + }); + + return dojox.math.stats; +}); |
