The Computer Language
Benchmarks Game

spectral-norm Kotlin program

source code

/* The Computer Language Benchmarks Game
   http://benchmarksgame.alioth.debian.org/
 
   mostly auto-converted from Jarkko Miettinen's Java program 
 */

import java.text.DecimalFormat
import java.text.NumberFormat

class spectralnorm {

    private fun Approximate(n: Int): Double {
        // create unit vector
        val u = DoubleArray(n)
        for (i in 0 until n) u[i] = 1.0

        // 20 steps of the power method
        val v = DoubleArray(n)
        for (i in 0 until n) v[i] = 0.0

        for (i in 0..9) {
            MultiplyAtAv(n, u, v)
            MultiplyAtAv(n, v, u)
        }

        // B=AtA         A multiplied by A transposed
        // v.Bv /(v.v)   eigenvalue of v
        var vBv = 0.0
        var vv = 0.0
        for (i in 0 until n) {
            vBv += u[i] * v[i]
            vv += v[i] * v[i]
        }

        return Math.sqrt(vBv / vv)
    }


    /* return element i,j of infinite matrix A */
    private fun A(i: Int, j: Int): Double {
        return 1.0 / ((i + j) * (i + j + 1) / 2 + i + 1)
    }

    /* multiply vector v by matrix A */
    private fun MultiplyAv(n: Int, v: DoubleArray, Av: DoubleArray) {
        for (i in 0 until n) {
            Av[i] = 0.0
            for (j in 0 until n) Av[i] += A(i, j) * v[j]
        }
    }

    /* multiply vector v by matrix A transposed */
    private fun MultiplyAtv(n: Int, v: DoubleArray, Atv: DoubleArray) {
        for (i in 0 until n) {
            Atv[i] = 0.0
            for (j in 0 until n) Atv[i] += A(j, i) * v[j]
        }
    }

    /* multiply vector v by matrix A and then by matrix A transposed */
    private fun MultiplyAtAv(n: Int, v: DoubleArray, AtAv: DoubleArray) {
        val u = DoubleArray(n)
        MultiplyAv(n, v, u)
        MultiplyAtv(n, u, AtAv)
    }

    companion object {

        private val formatter = DecimalFormat("#.000000000")

        @JvmStatic fun main(args: Array<String>) {
            var n = 100
            if (args.size > 0) n = Integer.parseInt(args[0])

            System.out.println(formatter.format(spectralnorm().Approximate(n)))
        }
    }
}
    

notes, command-line, and program output

NOTES:
64-bit Ubuntu quad core
Kotlin version 1.2.30-release-78 (JRE 10+46)
java 10 2018-03-20
Java(TM) SE Runtime Environment 18.3 (build 10+46)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10+46, mixed mode)


Wed, 21 Mar 2018 23:48:30 GMT

MAKE:
mv spectralnorm.kotlin spectralnorm.kt
/opt/src/kotlin-1.2.30/bin/kotlinc spectralnorm.kt -d spectralnorm.jar

5.27s to complete and log all make actions

COMMAND LINE:
/opt/src/jdk-10/bin/java -Xbootclasspath/a:/opt/src/kotlin-1.2.30/lib/kotlin-stdlib.jar:./spectralnorm.jar spectralnorm 5500

PROGRAM OUTPUT:
1.274224153