计算多项式:f(x)=a0 +ax+ax^2 +...+an*x^n
double fun(int n,double a[] ,double x )
{
double p=a[0];
for(int i=1;i<=n;i++){
p+=a[i]*Math.pow(x,i);
}
}
秦九韶方法:
f(x)=a0 +x(a1+ x(a2+ (.....x(an))) )
for(int i=n;i>0;i--){
p=a[i-1]+p*x
}
-----------------------
public class Duoxiangshi {
public static void main(String[] args) {
int Size=9999999;
double [] arr =new double[Size+1];
for (int i = 0; i <Size ; i++) {
arr[i]=i;
}
long begin=0;
begin=System.currentTimeMillis();
fun(Size,arr,1000);
long end=0;
end=System.currentTimeMillis();
System.out.println("time 1:"+(end-begin));
begin=System.currentTimeMillis();
fun2(Size,arr,1000);
end=System.currentTimeMillis();
System.out.println("time 2:"+(end-begin));
}
public static double fun(int n,double[] a ,double x )
{
double p=a[0];
for(int i=1;i<n;i++){
p+=a[i]*Math.pow(x,i);
}
return p;
}
// 秦九韶方法:
// f(x)=a0 +x(a1+ x(a2+ (.....x(an))) )
public static double fun2(int n,double[] a,double x)
{
double p=0.0;
for (int i = n; i >0 ; i--) {
p=a[i-1]+p*x;
}
return p;
}
}
时间差:
time 1:287
time 2:36