• java实现开根号算法


        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;
        }
  • 相关阅读:
    tarjan——强连通分量+缩点
    题解报告——Financial Crisis
    计算几何刷题计划(转)
    [bzoj1042] [HAOI2008]硬币购物
    [bzoj1584] [Usaco2009 Mar]Cleaning Up 打扫卫生
    bzoj 2783 JLOI2012 树
    bzoj 1150 [CTSC2007]数据备份Backup
    bzoj 1079 [SCOI2008]着色方案
    bzoj 2957 楼房重建
    bzoj 3208 花神的秒题计划I
  • 原文地址:https://www.cnblogs.com/-1007813544/p/8983293.html
Copyright © 2020-2023  润新知