有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Scala与Java中的样条插值性能

我从阿帕奇翻译了this spline interpolation algorithm。平民以我能想到的最直接的方式将数学从Java转换成Scala(见下文)。我最终得到的函数运行速度比原始Java代码慢2到3倍。我的猜测是,问题源于对Array.fill的调用产生的额外循环,但我想不出一个简单的方法来摆脱它们。关于如何使这段代码性能更好,有什么建议吗?(如果能以更简洁和/或功能性更强的方式来写,也会很好——我们也将感谢您在这方面的建议。)

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 < 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 => 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 < 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 >= 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 => Polynomial(Array(y(i), b(i), c(i), d(i))))
}

共 (0) 个答案