spectralnorm.scm 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #|
  2. The Great Computer Language Shootout
  3. http://shootout.alioth.debian.org/
  4. contributed by Java novice Jarkko Miettinen
  5. modified ~3 lines of the original C#-version
  6. by Isaac Gouy
  7. |#
  8. (define (Approximate (n :: int)) :: double
  9. (let ((u (double[] length: n)) ;; Create unit vector
  10. (v (double[] length: n))
  11. (vBv :: double 0)
  12. (vv :: double 0))
  13. (do ((i :: int 0 (+ i 1))) ((>= i n)) (set! (u i) 1))
  14. ;; 20 steps of the power method
  15. (do ((i :: int 0 (+ i 1))) ((>= i 10))
  16. (multiplyAtAv n u v)
  17. (multiplyAtAv n v u))
  18. ;; B=AtA A multiplied by A transposed
  19. ;; v.Bv /(v.v) eigenvalue of v
  20. (do ((i :: int 0 (+ i 1))) ((>= i n))
  21. (let ((vi (v i)))
  22. (set! vBv (+ vBv (* (u i) vi)))
  23. (set! vv (+ vv (* vi vi)))))
  24. (java.lang.Math:sqrt (/ vBv vv))))
  25. ;;; return element i,j of infinite matrix A
  26. (define (A (i :: int) (j :: int)) :: double
  27. (/ 1.0 (+ (quotient (* (+ i j) (+ i j 1)) 2) i 1)))
  28. ;;; multiply vector v by matrix A
  29. (define (multiplyAv (n :: int) (v :: double[]) (Av :: double[])) :: void
  30. (do ((i :: int 0 (+ i 1)))
  31. ((>= i n))
  32. (let ((sum :: double 0))
  33. (do ((j :: int 0 (+ j 1)))
  34. ((>= j n))
  35. (set! sum (+ sum (* (A i j) (v j)))))
  36. (set! (Av i) sum))))
  37. ;;; multiply vector v by matrix A transposed.
  38. (define (multiplyAtv (n :: int) (v :: double[]) (Atv :: double[])) :: void
  39. (do ((i :: int 0 (+ i 1)))
  40. ((>= i n))
  41. (let ((sum :: double 0))
  42. (do ((j :: int 0 (+ j 1)))
  43. ((>= j n))
  44. (set! sum (+ sum (* (A j i) (v j)))))
  45. (set! (Atv i) sum))))
  46. ;;; multiply vector v by matrix A and then by matrix A transposed.
  47. (define (multiplyAtAv (n :: int) (v :: double[]) (AtAv :: double[])) :: void
  48. (let ((u (double[] length: n)))
  49. (multiplyAv n v u)
  50. (multiplyAtv n u AtAv)))
  51. (format #t "~,9f~%~!" (Approximate (string->number (cadr (command-line)))))
  52. ; java.lang.System:out)