package com.beiguiyan.demo;


public class Demo6 {


public static void main(String[] args) {

System.out.println(exp(1.2));

System.out.println(expP(1.2));

System.out.println(Math.exp(1.2));

}


private static double sqrt(double db)

{

double new_guess=0;

double last_guess=0;

if (db < 0)

{

return -1;

}

new_guess = 1;

 do 

 {

 last_guess = new_guess;

 new_guess = (last_guess + db / last_guess) / 2;

 }while (new_guess != last_guess);

 

      return new_guess;

}

private static double exp(double x){

int i,k,m,t;

int xm=(int)x; 

double sum;

double e ;

double ef;

double z ;

double sub=x-xm;

 m=1;      //阶乘算法分母

    e=1.0;  //e的xm

 ef=1.0;  

 t=10;      //算法精度

 z=1;  //分子初始化

 sum=1;   


if (xm<0) {     //判断xm是否大于0?

  xm=(-xm); 

  for(k=0;k<xm;k++){ef*=Math.E;}

  e/=ef;

 } 

else { for(k=0;k<xm;k++){e*=Math.E;} }

 for(i=1;i<t;i++){

 m*=i; 

 z*=sub;  

 sum+=z/m;

}

return sum*e;

}

static double expP(double x)//计算e^x,实现系统的exp()功能 

{

   if(x==0) return 1;

   if(x<0) return 1/expP(-x); 

   double y=x,ex_p1=0,ex_p2=0,ex_p3=0,ex_p=0,ex_px=0,ex_tmp=1,dex_px=1,tmp;

   int l;

   for(l=1,tmp=1;((ex_px-ex_tmp)>1e-10 || (ex_px-ex_tmp)<-1e-10) && dex_px>1e-10;l++)

   {

       ex_tmp=ex_px;

       tmp*=y;

       tmp=tmp/l;

       ex_p1+=tmp;

       ex_p2=ex_p1+tmp*y/(l+1);

       ex_p3=ex_p2+tmp*y*y/(l+1)/(l+2);

       dex_px=ex_p3-ex_p2;

       ex_px=ex_p3-dex_px*dex_px/(ex_p3-2*ex_p2+ex_p1);

       }

       return ex_px+1;

}

}