Note that there are some explanatory texts on larger screens.

plurals
  1. POSpline Interpolation Performance in Scala vs Java
    primarykey
    data
    text
    <p>I translated <a href="http://commons.apache.org/math/api-2.2/src-html/org/apache/commons/math/analysis/interpolation/SplineInterpolator.html#line.53" rel="nofollow">this spline interpolation algorithm</a> from apache.commons.math from Java into Scala in the most straightforward way I could think of (see below). The function I ended up with runs 2 to 3 times slower than the original Java code. My guess is that the problem stems from the extra loops coming from the calls to <code>Array.fill</code>, but I can't think of a straightforward way to get rid of them. Any suggestions on how to make this code perform better? (It would also be nice to write it in a more concise and/or functional way -- suggestions on that front would be appreciated as well.)</p> <pre><code>type Real = Double def mySplineInterpolate(x: Array[Real], y: Array[Real]) = { if (x.length != y.length) throw new DimensionMismatchException(x.length, y.length) if (x.length &lt; 3) throw new NumberIsTooSmallException(x.length, 3, true) // Number of intervals. The number of data points is n + 1. val n = x.length - 1 // Differences between knot points val h = Array.tabulate(n)(i =&gt; x(i+1) - x(i)) var mu: Array[Real] = Array.fill(n)(0) var z: Array[Real] = Array.fill(n+1)(0) var i = 1 while (i &lt; n) { val g = 2.0 * (x(i+1) - x(i-1)) - h(i-1) * mu(i-1) mu(i) = h(i) / g z(i) = (3.0 * (y(i+1) * h(i-1) - y(i) * (x(i+1) - x(i-1))+ y(i-1) * h(i)) / (h(i-1) * h(i)) - h(i-1) * z(i-1)) / g i += 1 } // cubic spline coefficients -- b is linear, c quadratic, d is cubic (original y's are constants) var b: Array[Real] = Array.fill(n)(0) var c: Array[Real] = Array.fill(n+1)(0) var d: Array[Real] = Array.fill(n)(0) var j = n-1 while (j &gt;= 0) { c(j) = z(j) - mu(j) * c(j + 1) b(j) = (y(j+1) - y(j)) / h(j) - h(j) * (c(j+1) + 2.0 * c(j)) / 3.0 d(j) = (c(j+1) - c(j)) / (3.0 * h(j)) j -= 1 } Array.tabulate(n)(i =&gt; Polynomial(Array(y(i), b(i), c(i), d(i)))) } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload