Sunday, January 20, 2013

Find n-th Root of a Number 求一個數的 n 次方根


要求一個數的 n 次方根, 有很多 programing language 都有 Math.pow(x,y) 的 library. 如要求 x 的 n 次方根, 在 Java 只需用 Math.pow(x, 1.0/n) 的 function 就得了. To find the n-th root of a number, usually many programming languages consist the Math.pow(x,y) library.
In Java, simply type Math.pow(x, 1.0/n) can find the n-th root of x.






但如果要用 Numerical Method 來找, 筆者在 Wikipedia 的 nth root algorithm 找到一個 algorithm 是由 Newton's Method derive 出來的.

這是我 RootNewton.java 的 source code:
On the other hand, to find it using Numerical Method, I found the n-th root algorithm on Wikipedia which is derived using Newton's Method.

This is my source code RootNewton.java



我覺得我的 iteration 寫得比較長氣, 如果讀者有一些比較好的辦法, 請你告訴我吧.
But I find this code is a little bit verbose, if you know how to make it better, please let me know.