模組 Newton

newton.rb

透過 Newton 方法來求解非線性代數方程式系統 f = 0。此程式不依賴於 BigDecimal

呼叫方式

  n = nlsolve(f,x)
where n is the number of iterations required,
      x is the initial value vector
      f is an Object which is used to compute the values of the equations to be solved.

必須提供下列方法

f.values(x)

傳回 x 中所有函數的值

f.zero

傳回 0.0

f.one

傳回 1.0

f.two

傳回 2.0

f.ten

傳回 10.0

f.eps

傳回用於判斷兩個值是否相等的收斂準則 (epsilon 值)。如果 |a-b| < epsilon,則兩個值會被視為相等。

結束時,x 會是解向量。

公開實例方法

nlsolve(f,x) 按一下以切換來源

請參閱 Newton

# File ext/bigdecimal/lib/bigdecimal/newton.rb, line 44
def nlsolve(f,x)
  nRetry = 0
  n = x.size

  f0 = f.values(x)
  zero = f.zero
  one  = f.one
  two  = f.two
  p5 = one/two
  d  = norm(f0,zero)
  minfact = f.ten*f.ten*f.ten
  minfact = one/minfact
  e = f.eps
  while d >= e do
    nRetry += 1
    # Not yet converged. => Compute Jacobian matrix
    dfdx = jacobian(f,f0,x)
    # Solve dfdx*dx = -f0 to estimate dx
    dx = lusolve(dfdx,f0,ludecomp(dfdx,n,zero,one),zero)
    fact = two
    xs = x.dup
    begin
      fact *= p5
      if fact < minfact then
        raise "Failed to reduce function values."
      end
      for i in 0...n do
        x[i] = xs[i] - dx[i]*fact
      end
      f0 = f.values(x)
      dn = norm(f0,zero)
    end while(dn>=d)
    d = dn
  end
  nRetry
end