n乗根を求めてみた。

30分プログラム、その781。n乗根を求めてみた。
n乗根なんてどうやって求めるんだろう、と思って調べてみたけど、ニュートン法で解いてた。あああ、なるほど。

使い方

scala> NthRoot.nthRoot(4,2)
res7: Double = 2.0000000929222947

scala> NthRoot.nthRoot(8,3)
res8: Double = 2.000000001071189

ソースコード

import scala.math

object NthRoot{
  def newton[T](improve : T => T, good : (T,T) => Boolean, init : T) : T = {
    val next = improve(init)
    if(good(init, next))
      next
    else
      newton(improve,good,next)
  }

  def nthRoot(x : Double, n : Int) : Double = {
    newton((y : Double) => ((n-1)*y + x / math.pow(y,n-1))/n,
	   (x : Double, y : Double) => math.abs(x - y) < 0.001,
	   x)
  }
}