I have 2 arrays of Doubles of the same length. Array a is filled with some data, array b is to be calculated.
Each element of the array b equals a corresponding value from array a plus a weighted sum of all preceding elements in the array b.
A weighted sum is calculated by adding all those elements each multiplied by a coefficient which equals its distance from the current element we calculate divided by number of elements in the preceding subset.
To implement this I loop through the whole preceding subset for each element I calculate.
Can this be optimized? I have not enough maths skills, but I suspect that I could only use the first preceding element to calculate every next as every element is already derived from the preceding set and contains all the information of it already weighted. Maybe I can just adjust the weight formula and get the same result without a second level looping?
This seems to be an example in Scala (I am not sure if it is correct :-]). As the real project uses negative indices, treat a(1) and a(2) as preceding a(0) in terms of the task written above.
import scala.Double.NaN
val a = Array[Double] (8.5, 3.4, 7.1, 5.12, 0.14, 5)
val b = Array[Double] (NaN, NaN, NaN, NaN, NaN, 5)
var i = b.length - 2
while (i >= 0) {
b(i) = a(i) + {
var succession = 0.0
var j = 1
while (i + j < b.length) {
succession += b (i+j) * (1.0-j.toDouble/(b.length - i))
j += 1
}
succession
}
i -= 1
}
b.foreach((n : Double) => println(n))