开平方的七种算法

来源:互联网 发布:淘宝用的什么系统 编辑:程序博客网 时间:2024/05/17 02:34

sqrt()函数,是绝大部分语言支持的常用函数,它实现的是开方运算;开方运算最早是在我国魏晋时数学家刘徽所著的《九章算术》被提及。今天写了几个函数加上国外大神的几个神级程序带大家领略sqrt的神奇之处。


1.古人算法(暴力法)  

原理:从0开始0.00001,000002…一个一个试,直到找到x的平方根,代码如下:

[java] view plain copy
print?
  1. public class APIsqrt {  
  2.   
  3.     static double baoliSqrt(double x) {  
  4.   
  5.         final double _JINGDU = 1e-6;  
  6.         double i;  
  7.         for (i = 0; Math.abs(x - i * i) > _JINGDU; i += _JINGDU)  
  8.             ;  
  9.         return i;  
  10.     }  
  11.   
  12.     public static void main(String[] args) {  
  13.         double x = 3;  
  14.         double root = baoliSqrt(x);  
  15.         System.out.println(root);  
  16.     }  
  17. }  
public class APIsqrt {    static double baoliSqrt(double x) {        final double _JINGDU = 1e-6;        double i;        for (i = 0; Math.abs(x - i * i) > _JINGDU; i += _JINGDU)            ;        return i;    }    public static void main(String[] args) {        double x = 3;        double root = baoliSqrt(x);        System.out.println(root);    }}

测试结果:

1.7320509999476947

2.牛顿迭代法

计算机科班出身的童鞋可能首先会想到的是《数值分析》中的牛顿迭代法求平方根。原理是:随意选一个数比如说8,要求根号3,我们可以这么算:

(8 + 3/8) = 4.1875

(4.1875 + 3/4.1875) = 2.4519

(2.4519 + 3/2.4519) = 1.837

(1.837 + 3/1.837) = 1.735

做了4步基本算出了近似值了,这种迭代的方式就是传说中的牛顿迭代法了,代码如下:

[java] view plain copy
print?
  1. public class APIsqrt {  
  2.   
  3.     static double newtonSqrt(double x) {  
  4.   
  5.         if (x < 0) {  
  6.             System.out.println(”负数没事开什么方”);  
  7.             return -1;  
  8.         }  
  9.         if (x == 0)  
  10.             return 0;  
  11.   
  12.         double _avg = x;  
  13.         double last_avg = Double.MAX_VALUE;  
  14.         final double _JINGDU = 1e-6;  
  15.   
  16.         while (Math.abs(_avg - last_avg) > _JINGDU) {  
  17.             last_avg = _avg;  
  18.             _avg = (_avg + x / _avg) / 2;  
  19.         }  
  20.         return _avg;  
  21.     }  
  22.   
  23.     public static void main(String[] args) {  
  24.         double x = 3;  
  25.         double root = newtonSqrt(x);  
  26.         System.out.println(root);  
  27.     }  
  28. }  
public class APIsqrt {    static double newtonSqrt(double x) {        if (x < 0) {            System.out.println("负数没事开什么方");            return -1;        }        if (x == 0)            return 0;        double _avg = x;        double last_avg = Double.MAX_VALUE;        final double _JINGDU = 1e-6;        while (Math.abs(_avg - last_avg) > _JINGDU) {            last_avg = _avg;            _avg = (_avg + x / _avg) / 2;        }        return _avg;    }    public static void main(String[] args) {        double x = 3;        double root = newtonSqrt(x);        System.out.println(root);    }}

测试结果:

1.7320508075688772


3.暴力-牛顿综合法

原理:还是以根号3为例,先用暴力法讲根号3逼近到1.7,然后再利用上述的牛顿迭代法。虽然没有用牛顿迭代好,但是也为我们提供一种思路。代码如下:

[java] view plain copy
print?
  1. public class APIsqrt {  
  2.   
  3.     static double baoliAndNewTonSqrt(double x) {  
  4.       
  5.         if (x < 0) {  
  6.             System.out.println(”负数没事开什么方”);  
  7.             return -1;  
  8.         }  
  9.         if (x == 0)  
  10.             return 0;  
  11.   
  12.         double i = 0;  
  13.         double _avg;  
  14.         double last_avg = Double.MAX_VALUE;  
  15.         for (i = 0; i*i < x; i += 0.1);  
  16.         _avg = i;  
  17.   
  18.         final double _JINGDU = 1e-6;  
  19.   
  20.         while (Math.abs(_avg - last_avg) > _JINGDU) {  
  21.             last_avg = _avg;  
  22.             _avg = (_avg + x / _avg) / 2;  
  23.         }  
  24.         return _avg;  
  25.     }  
  26.       
  27.     public static void main(String[] args) {  
  28.         double x = 3;  
  29.         double root = baoliAndNewTonSqrt(x);  
  30.         System.out.println(root);  
  31.     }  
  32. }  
public class APIsqrt {    static double baoliAndNewTonSqrt(double x) {        if (x < 0) {            System.out.println("负数没事开什么方");            return -1;        }        if (x == 0)            return 0;        double i = 0;        double _avg;        double last_avg = Double.MAX_VALUE;        for (i = 0; i*i < x; i += 0.1);        _avg = i;        final double _JINGDU = 1e-6;        while (Math.abs(_avg - last_avg) > _JINGDU) {            last_avg = _avg;            _avg = (_avg + x / _avg) / 2;        }        return _avg;    }    public static void main(String[] args) {        double x = 3;        double root = baoliAndNewTonSqrt(x);        System.out.println(root);    }}

测试结果:

1.7320508075689423


4.二分开方法

原理:还是以3举例:

(0+3)/2 = 1.5, 1.5^2 = 2.25, 2.25 < 3;

(1.5+3)/2 = 2.25, 2.25^2 = 5.0625, 5.0625 > 3;

(1.5+2.25)/2 = 1.875, 1.875^2 = 3.515625; 3.515625>3;

.

.

.

直到前后两次平均值只差小于自定义精度为止,代码如下:

[java] view plain copy
print?
  1. public class APIsqrt {  
  2.   
  3.     static double erfenSqrt(double x) {  
  4.   
  5.         if (x < 0) {  
  6.             System.out.println(”负数没事开什么方”);  
  7.             return -1;  
  8.         }  
  9.         if (x == 0)  
  10.             return 0;  
  11.   
  12.         final double _JINGDU = 1e-6;  
  13.         double _low = 0;  
  14.         double _high = x;  
  15.         double _mid = Double.MAX_VALUE;  
  16.         double last_mid = Double.MIN_VALUE;  
  17.   
  18.         while (Math.abs(_mid - last_mid) > _JINGDU) {  
  19.   
  20.             last_mid = _mid;  
  21.             _mid = (_low + _high) / 2;  
  22.             if (_mid * _mid > x)  
  23.                 _high = _mid;  
  24.             if (_mid * _mid < x)  
  25.                 _low = _mid;  
  26.   
  27.         }  
  28.         return _mid;  
  29.   
  30.     }  
  31.   
  32.     public static void main(String[] args) {  
  33.         double x = 3;  
  34.         double root = erfenSqrt(x);  
  35.         System.out.println(root);  
  36.     }  
  37. }  
public class APIsqrt {    static double erfenSqrt(double x) {        if (x < 0) {            System.out.println("负数没事开什么方");            return -1;        }        if (x == 0)            return 0;        final double _JINGDU = 1e-6;        double _low = 0;        double _high = x;        double _mid = Double.MAX_VALUE;        double last_mid = Double.MIN_VALUE;        while (Math.abs(_mid - last_mid) > _JINGDU) {            last_mid = _mid;            _mid = (_low + _high) / 2;            if (_mid * _mid > x)                _high = _mid;            if (_mid * _mid < x)                _low = _mid;        }        return _mid;    }    public static void main(String[] args) {        double x = 3;        double root = erfenSqrt(x);        System.out.println(root);    }}

测试结果:

1.732051134109497


5.计算 (int)(sqrt(x))算法

PS:此算法非博主所写
原理:空间换时间,细节请大家自行探究,代码如下:

[java] view plain copy
print?
  1. public class APIsqrt2 {  
  2.     final static int[] table = { 01622273235394245485053,  
  3.             5557596164656769717375767880818384,  
  4.             8687899091939496979899101102103104,  
  5.             106107108109110112113114115116117118119,  
  6.             120121122123124125126128128129130131132,  
  7.             133134135136137138139140141142143144144,  
  8.             145146147148149150150151152153154155155,  
  9.             156157158159160160161162163163164165166,  
  10.             167167168169170170171172173173174175176,  
  11.             176177178178179180181181182183183184185,  
  12.             185186187187188189189190191192192193193,  
  13.             194195195196197197198199199200201201202,  
  14.             203203204204205206206207208208209209210,  
  15.             211211212212213214214215215216217217218,  
  16.             218219219220221221222222223224224225225,  
  17.             226226227227228229229230230231231232232,  
  18.             233234234235235236236237237238238239240,  
  19.             240241241242242243243244244245245246246,  
  20.             247247248248249249250250251251252252253,  
  21.             253254254255 };  
  22.   
  23.     /** 
  24.      * A faster replacement for (int)(java.lang.Math.sqrt(x)). Completely 
  25.      * accurate for x < 2147483648 (i.e. 2^31)… 
  26.      */  
  27.     static int sqrt(int x) {  
  28.         int xn;  
  29.   
  30.         if (x >= 0x10000) {  
  31.             if (x >= 0x1000000) {  
  32.                 if (x >= 0x10000000) {  
  33.                     if (x >= 0x40000000) {  
  34.                         xn = table[x >> 24] << 8;  
  35.                     } else {  
  36.                         xn = table[x >> 22] << 7;  
  37.                     }  
  38.                 } else {  
  39.                     if (x >= 0x4000000) {  
  40.                         xn = table[x >> 20] << 6;  
  41.                     } else {  
  42.                         xn = table[x >> 18] << 5;  
  43.                     }  
  44.                 }  
  45.   
  46.                 xn = (xn + 1 + (x / xn)) >> 1;  
  47.                 xn = (xn + 1 + (x / xn)) >> 1;  
  48.                 return ((xn * xn) > x) ? –xn : xn;  
  49.             } else {  
  50.                 if (x >= 0x100000) {  
  51.                     if (x >= 0x400000) {  
  52.                         xn = table[x >> 16] << 4;  
  53.                     } else {  
  54.                         xn = table[x >> 14] << 3;  
  55.                     }  
  56.                 } else {  
  57.                     if (x >= 0x40000) {  
  58.                         xn = table[x >> 12] << 2;  
  59.                     } else {  
  60.                         xn = table[x >> 10] << 1;  
  61.                     }  
  62.                 }  
  63.   
  64.                 xn = (xn + 1 + (x / xn)) >> 1;  
  65.   
  66.                 return ((xn * xn) > x) ? –xn : xn;  
  67.             }  
  68.         } else {  
  69.             if (x >= 0x100) {  
  70.                 if (x >= 0x1000) {  
  71.                     if (x >= 0x4000) {  
  72.                         xn = (table[x >> 8]) + 1;  
  73.                     } else {  
  74.                         xn = (table[x >> 6] >> 1) + 1;  
  75.                     }  
  76.                 } else {  
  77.                     if (x >= 0x400) {  
  78.                         xn = (table[x >> 4] >> 2) + 1;  
  79.                     } else {  
  80.                         xn = (table[x >> 2] >> 3) + 1;  
  81.                     }  
  82.                 }  
  83.   
  84.                 return ((xn * xn) > x) ? –xn : xn;  
  85.             } else {  
  86.                 if (x >= 0) {  
  87.                     return table[x] >> 4;  
  88.                 }  
  89.             }  
  90.         }  
  91.   
  92.         return -1;  
  93.     }  
  94.     public static void main(String[] args){  
  95.         System.out.println(sqrt(65));  
  96.           
  97.     }  
  98. }  
public class APIsqrt2 {    final static int[] table = { 0, 16, 22, 27, 32, 35, 39, 42, 45, 48, 50, 53,            55, 57, 59, 61, 64, 65, 67, 69, 71, 73, 75, 76, 78, 80, 81, 83, 84,            86, 87, 89, 90, 91, 93, 94, 96, 97, 98, 99, 101, 102, 103, 104,            106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118, 119,            120, 121, 122, 123, 124, 125, 126, 128, 128, 129, 130, 131, 132,            133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 144,            145, 146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155, 155,            156, 157, 158, 159, 160, 160, 161, 162, 163, 163, 164, 165, 166,            167, 167, 168, 169, 170, 170, 171, 172, 173, 173, 174, 175, 176,            176, 177, 178, 178, 179, 180, 181, 181, 182, 183, 183, 184, 185,            185, 186, 187, 187, 188, 189, 189, 190, 191, 192, 192, 193, 193,            194, 195, 195, 196, 197, 197, 198, 199, 199, 200, 201, 201, 202,            203, 203, 204, 204, 205, 206, 206, 207, 208, 208, 209, 209, 210,            211, 211, 212, 212, 213, 214, 214, 215, 215, 216, 217, 217, 218,            218, 219, 219, 220, 221, 221, 222, 222, 223, 224, 224, 225, 225,            226, 226, 227, 227, 228, 229, 229, 230, 230, 231, 231, 232, 232,            233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238, 239, 240,            240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246,            247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253,            253, 254, 254, 255 };    /**     * A faster replacement for (int)(java.lang.Math.sqrt(x)). Completely     * accurate for x < 2147483648 (i.e. 2^31)...     */    static int sqrt(int x) {        int xn;        if (x >= 0x10000) {            if (x >= 0x1000000) {                if (x >= 0x10000000) {                    if (x >= 0x40000000) {                        xn = table[x >> 24] << 8;                    } else {                        xn = table[x >> 22] << 7;                    }                } else {                    if (x >= 0x4000000) {                        xn = table[x >> 20] << 6;                    } else {                        xn = table[x >> 18] << 5;                    }                }                xn = (xn + 1 + (x / xn)) >> 1;                xn = (xn + 1 + (x / xn)) >> 1;                return ((xn * xn) > x) ? --xn : xn;            } else {                if (x >= 0x100000) {                    if (x >= 0x400000) {                        xn = table[x >> 16] << 4;                    } else {                        xn = table[x >> 14] << 3;                    }                } else {                    if (x >= 0x40000) {                        xn = table[x >> 12] << 2;                    } else {                        xn = table[x >> 10] << 1;                    }                }                xn = (xn + 1 + (x / xn)) >> 1;                return ((xn * xn) > x) ? --xn : xn;            }        } else {            if (x >= 0x100) {                if (x >= 0x1000) {                    if (x >= 0x4000) {                        xn = (table[x >> 8]) + 1;                    } else {                        xn = (table[x >> 6] >> 1) + 1;                    }                } else {                    if (x >= 0x400) {                        xn = (table[x >> 4] >> 2) + 1;                    } else {                        xn = (table[x >> 2] >> 3) + 1;                    }                }                return ((xn * xn) > x) ? --xn : xn;            } else {                if (x >= 0) {                    return table[x] >> 4;                }            }        }        return -1;    }    public static void main(String[] args){        System.out.println(sqrt(65));    }}
测试结果:8


6.最快的sqrt算法

PS:此算法非博主所写

这个算法很有名,大家可能也见过,作者是开发游戏的,图形算法中经常用到sqrt,作者才写了一个神级算法,和他那神秘的0x5f3759df,代码如下

[cpp] view plain copy
print?
  1. #include <math.h>  
  2. float InvSqrt(float x)  
  3. {  
  4.  float xhalf = 0.5f*x;  
  5.  int i = *(int*)&x; // get bits for floating VALUE  
  6.  i = 0x5f375a86- (i>>1); // gives initial guess y0  
  7.  x = *(float*)&i; // convert bits BACK to float  
  8.  x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy  
  9.  return x;  
  10. }  
  11.   
  12. int main()  
  13. {  
  14.   printf(”%lf”,1/InvSqrt(3));  
  15.   
  16.    return 0;  
  17. }  
#include <math.h>float InvSqrt(float x){ float xhalf = 0.5f*x; int i = *(int*)&x; // get bits for floating VALUE i = 0x5f375a86- (i>>1); // gives initial guess y0 x = *(float*)&i; // convert bits BACK to float x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy return x;}int main(){  printf("%lf",1/InvSqrt(3));   return 0;}
测试结果:


感兴趣的朋友可以参考http://wenku.baidu.com/view/a0174fa20029bd64783e2cc0.html  是作者解释这个算法的14页论文《Fast Inverse Square Root》


7.一个与算法6相似的算法

PS:此算法非博主所写

代码如下:

[cpp] view plain copy
print?
  1. #include <math.h>  
  2. float SquareRootFloat(float number) {  
  3.     long i;  
  4.     float x, y;  
  5.     const float f = 1.5F;  
  6.   
  7.     x = number * 0.5F;  
  8.     y  = number;  
  9.     i  = * ( long * ) &y;  
  10.     i  = 0x5f3759df - ( i >> 1 );  
  11.     y  = * ( float * ) &i;  
  12.     y  = y * ( f - ( x * y * y ) );  
  13.     y  = y * ( f - ( x * y * y ) );  
  14.     return number * y;  
  15. }  
  16.   
  17. int main()  
  18. {  
  19.   printf(”%f”,SquareRootFloat(3));  
  20.   
  21.    return 0;  
  22. }  
#include <math.h>float SquareRootFloat(float number) {    long i;    float x, y;    const float f = 1.5F;    x = number * 0.5F;    y  = number;    i  = * ( long * ) &y;    i  = 0x5f3759df - ( i >> 1 );    y  = * ( float * ) &i;    y  = y * ( f - ( x * y * y ) );    y  = y * ( f - ( x * y * y ) );    return number * y;}int main(){  printf("%f",SquareRootFloat(3));   return 0;}
测试结果:





==================================================================================================

  作者:nash_  欢迎转载,与人分享是进步的源泉!

  转载请保留原文地址http://blog.csdn.net/nash_/article/details/8217866

===================================================================================================

原创粉丝点击