java實現開根號演算法

來源:互聯網
上載者:User

標籤:time   static   stat   演算法   code   abs   out   public   newton   

    public static void main(String[] args) {        long start = System.currentTimeMillis();        double target=9876543212345d;        double result =sqrt(target);        System.out.println("sqrt耗時:"+(System.currentTimeMillis()-start)+",result:"+result);                start=System.currentTimeMillis();        result =SqrtByBisection(target, 0);        System.out.println("SqrtByBisection耗時:"+(System.currentTimeMillis()-start)+",result:"+result);                start=System.currentTimeMillis();        result = SqrtByNewton(target, 0);        System.out.println("SqrtByNewton耗時:"+(System.currentTimeMillis()-start)+",result:"+result);    }        //牛頓迭代法    public static double SqrtByNewton(double target,double eps){        double Xa=target,Xb;        do {            Xb = Xa;            Xa = (Xa+target/Xa)/2;        } while (fabsf(Xa,Xb)>eps);        return Xa;    }    //二分法  精度是指兩次mid值的差值    public static double SqrtByBisection(double target,double eps){        double min=1,max=target;        double mid =(min+max)/2;        double anMid;        do {            if(mid*mid>target){                max=mid;            }else{                min=mid;            }            anMid=mid;            mid=(max+min)/2;        } while (fabsf(anMid,mid)>eps);        return mid;    }            public static double sqrt(double d){        double a = 0.1;        double x1,x2=0;        while (a*a<=d) {            a+=0.1;        }         x1=a;        for (int i = 0; i < 10; i++) {            x2=d;            x2/=x1;//x2 = x2/x1;            x2+=x1;            x2/=2;            x1=x2;        }        return x2;    }        public static double fabsf(double a,double b){        if(a>b){            return a-b;        }else            return b-a;    }

 

java實現開根號演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.