1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00
v/examples/spectral.v

71 lines
1.2 KiB
V
Raw Normal View History

2019-07-06 17:29:50 +03:00
/*
https://benchmarksgame-team.pages.debian.net/benchmarksgame/performance/spectralnorm.html
Added: Pradeep Verghese
Benchmarks:
2019-07-06 18:13:34 +03:00
Used v -prod spectral.v
Command: time ./spectral 5500
Output: 1.274224153
2019-07-06 17:29:50 +03:00
2019-07-06 18:13:34 +03:00
Time: 11.67s user 0.02s system 99% cpu 11.721 total
2019-07-06 17:29:50 +03:00
*/
module main
2019-07-06 17:29:50 +03:00
import math
import os
fn evala(i, j int) int {
return ((i + j) * (i + j + 1) / 2 + i + 1)
2019-07-06 17:29:50 +03:00
}
2019-12-03 11:52:38 +03:00
fn times(v mut []f64, u []f64) {
for i in 0..v.len {
mut a := f64(0)
for j in 0..u.len {
a += u[j] / f64(evala(i, j))
}
v[i] = a
}
2019-07-06 17:29:50 +03:00
}
2019-12-03 11:52:38 +03:00
fn times_trans(v mut []f64, u []f64) {
for i in 0..v.len {
mut a := f64(0)
for j in 0..u.len {
a += u[j] / f64(evala(j, i))
}
v[i] = a
}
2019-07-06 17:29:50 +03:00
}
2019-12-03 11:52:38 +03:00
fn a_times_transp(v mut []f64, u []f64) {
mut x := [f64(0)].repeat(u.len)
times(mut x, u)
times_trans(mut v, x)
}
2019-07-06 17:29:50 +03:00
fn main() {
args := os.args
mut n := int(0)
if args.len == 2 {
n = args[1].int()
}
else {
n = 0
}
mut u := [f64(1.0)].repeat(n)
mut v := [f64(1.0)].repeat(n)
for i in 0..10 {
a_times_transp(mut v, u)
a_times_transp(mut u, v)
}
mut vbv := f64(0)
mut vv := f64(0)
for i in 0..n {
vbv += u[i] * v[i]
vv += v[i] * v[i]
}
ans := math.sqrt(vbv / vv)
println('${ans:0.9f}')
2019-07-06 17:29:50 +03:00
}