Kotlin JVM #1 — Spectral Norm
Calculate the spectral norm of an infinite matrix using the power method.
| Time | 1,043.4 ms |
|---|---|
| CPU time | 1,082.7 ms |
| Peak memory | 46,600 KB |
| gz | 519 bytes — comments removed, gzipped |
| Style | ★★☆☆☆ |
| Implementation | Kotlin — Kotlin (JVM) 2.4.20 |
| By | sysop- |
| Submitted | September 24, 2026 |
Style assessment
This is a mechanical Java port: lowercase class name, PascalCase methods (Approximate, MultiplyAtAv), Integer.parseInt, System.out.println, DecimalFormat, and a @JvmStatic companion-object main all flout Kotlin conventions, and the explicit zero-fill of v is dead code since DoubleArray(n) is already zeroed. A top-level fun main, camelCase functions, args[0].toInt(), println, kotlin.math.sqrt, u.fill(1.0), and dropping the wrapper class would make it idiomatic Kotlin.
Source
79 lines · Download spectral-norm-kotlin-jvm-1.kt
/* 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)))
}
}
}