求根运算主要有两种方法:
一种是二分法,这个是比较好理解的
一种是牛顿迭代法,这个有点晦涩,迭代的公式是这样的
其中
/**
* 求根运算
*/
public class CalRootTest {
public static void main(String[] args) {
System.out.println(byBinarySearch(81,2));
System.out.println(byNewtonIterator(81,2));
}
/**
* 二分法
* @param sum
* @param power
* @return
*/
public static int byBinarySearch(int sum,int power){
int low=0,high=sum,mid,temp;
while (low<=high){
mid = (low+high)/2;
temp = calByPower(mid,power);
if(temp==sum){
return mid;
}else if(temp>sum){
high = mid-1;
}else{
low = mid+1;
}
}
return high;
}
/**
* 牛顿迭代法
* f(n) = n^t-T
* f'(n) = tn^(t-1)
* nextN = n - f(n)/f'(n) = n - (n^t-T)/tn^(t-1)
* @param sum
* @param t
* @return
*/
public static int byNewtonIterator(int sum,int t){
return (int) byNewtonIterator(sum,sum,t);
}
public static double byNewtonIterator(double n, double sum,int t){
double res = n - (calByPower(n,t)-sum)/(t*calByPower(n,t-1));
if(res==n){
return res;
}else if(res>n){
return n;
}else{
return byNewtonIterator(res,sum,t);
}
}
private static int calByPower(double t,int power){
int count = 0, target = 1;
while (count<power){
target *= t;
count++;
}
return target;
}
}