Created
February 17, 2012 23:49
-
-
Save swannodette/1856319 to your computer and use it in GitHub Desktop.
spectral_norm.cljs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns alioth.spectral-norm) | |
(set! *unchecked-math* true) | |
(set! *print-fn* js/console.log) | |
(defn a [i j] | |
(/ 1.0 (+ (/ (* (+ i j) (+ i j 1)) 2.0) i 1))) | |
(defn mul-av [n v av] | |
(dotimes [i n] | |
(aset av i 0.0) | |
(dotimes [j n] | |
(aset av i (+ (aget av i) (* (a i j) (aget v j))))))) | |
(defn mul-atv [n v atv] | |
(dotimes [i n] | |
(aset atv i 0.0) | |
(dotimes [j n] | |
(aset atv i (+ (aget atv i) (* (a j i) (aget v j))))))) | |
(defn mul-atav [n v atav] | |
(let [u (array n)] | |
(mul-av n v u) | |
(mul-atv n u atav))) | |
(defn approximate [n] | |
(let [u (array n) | |
v (array n)] | |
(dotimes [i n] (aset u i 1.0) (aset v i 0.0)) | |
(dotimes [i 10] | |
(mul-atav n u v) | |
(mul-atav n v u)) | |
(loop [i 0 vbv 0.0 vv 0.0] | |
(if (< i n) | |
(recur (inc i) | |
(+ vbv (* (aget u i) (aget v i))) | |
(+ vv (* (aget v i) (aget v i)))) | |
(Math/sqrt (/ vbv vv)))))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function A(i,j) { | |
return 1/((i+j)*(i+j+1)/2+i+1); | |
} | |
function Au(u,v) { | |
for (var i=0; i<u.length; ++i) { | |
var t = 0; | |
for (var j=0; j<u.length; ++j) | |
t += A(i,j) * u[j]; | |
v[i] = t; | |
} | |
} | |
function Atu(u,v) { | |
for (var i=0; i<u.length; ++i) { | |
var t = 0; | |
for (var j=0; j<u.length; ++j) | |
t += A(j,i) * u[j]; | |
v[i] = t; | |
} | |
} | |
function AtAu(u,v,w) { | |
Au(u,w); | |
Atu(w,v); | |
} | |
function spectralnorm(n) { | |
var i, u=[], v=[], w=[], vv=0, vBv=0; | |
for (i=0; i<n; ++i) { | |
u[i] = 1; v[i] = w[i] = 0; | |
} | |
for (i=0; i<10; ++i) { | |
AtAu(u,v,w); | |
AtAu(v,u,w); | |
} | |
for (i=0; i<n; ++i) { | |
vBv += u[i]*v[i]; | |
vv += v[i]*v[i]; | |
} | |
return Math.sqrt(vBv/vv); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment