模块 Newton

newton.rb

使用牛顿法求解非线性代数方程组 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 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