File: spectralnorm.scala-2.scala

package info (click to toggle)
scala 2.7.7.dfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 75,804 kB
  • ctags: 1,852
  • sloc: java: 7,762; xml: 6,608; sh: 1,723; cs: 158; makefile: 9; ansic: 6
file content (74 lines) | stat: -rw-r--r-- 1,465 bytes parent folder | download
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
/* The Computer Language Shootout
   http://shootout.alioth.debian.org/
   contributed by Isaac Gouy 
*/

object SpectralNorm {

   def main(args: Array[String]) {
      val n = Integer parseInt(args(0))

      Console.printf("%.9f\n", 
         new SpectralNorm() approximate(n) )
   }
}

class SpectralNorm(){

   type Vector = Array[Double]

   def approximate(n: Int)= {
      val u = new Vector(n)
      var i = 0; 
      while (i < n){ u(i) = 1.0; i = i+1 }

      val v = new Vector(n)

      i = 0
      while (i < 10){ 
         multiplyAtAv(n,u,v)
         multiplyAtAv(n,v,u)
         i = i+1
      }

      var vbv = 0.0; var vv = 0.0
      i = 0
      while (i < n){ 
         vbv = vbv + u(i)*v(i)
         vv = vv + v(i)*v(i)
         i = i+1
      }

      Math sqrt(vbv/vv)
   }


   def a(i: Int, j: Int) = 1.0/((i+j)*(i+j+1)/2 +i+1)

   def multiplyAv(n: Int, v: Vector, av: Vector) = {
      var i = 0
      while (i < n){
         av(i) = 0.0
         var j = 0
         while (j < n){ av(i) = av(i) + a(i,j) * v(j); j = j+1 }
         i = i+1     
      }
   }

   def multiplyAtv(n: Int, v: Vector, atv: Vector) = {
      var i = 0
      while (i < n){
         atv(i) = 0.0
         var j = 0
         while (j < n){ atv(i) = atv(i) + a(j,i) * v(j); j = j+1 }
         i = i+1     
      }
   }

   def multiplyAtAv(n: Int, v: Vector, atav: Vector) = {
      val u = new Vector(n)
      multiplyAv(n,v,u)
      multiplyAtv(n,u,atav)
   }

}