Seven mathematical algorithms

Source: Internet
Author: User

The SQRT () function is a common function supported by most languages. It implements open-side operations. The open-side operations were first mentioned in chapter 9 arithmetic by Liu Hui, a mathematician in China's Wei and Jin Dynasties. Today, I wrote several functions and several God-class programs from other countries to help you understand the magic of SQRT.


1. Ancients algorithm (Violence Law)

Principle: from 0 to 0.00001, 000002... try one by one until the square root of X is found. The Code is as follows:

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);}}

Test results:

1.7320509999476947

2. Newton Iteration Method

The first thing that comes to mind in computer science is the Newton Iteration Method in Numerical Analysis for the square root. The principle is: select a random number, for example, 8, with the root number 3. We can calculate it as follows:

(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

After four steps, the approximate values are basically calculated. This iteration method is the legendary Newton iteration method. The Code is as follows:

Public class apisqrt {static double newtonsqrt (Double X) {If (x <0) {system. out. println ("no way to enable negative numbers"); 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 );}}

Test results:

1.7320508075688772

3. Violence-Newton Synthesis Method

Principle: take root 3 as an example. Use the violence law to tell root 3 to approach 1.7, and then use the above Newton Iteration Method. Although Newton's iteration is not good, it also provides us with an idea. The Code is as follows:

Public class apisqrt {static double baoliandnewtonsqrt (Double X) {If (x <0) {system. out. println ("no way to enable negative numbers"); 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 );}}

Test results:

1.7320508075689423


4. Two separate methods

Principle: Take 3 For example:

(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;

.

.

.

The Code is as follows:

Public class apisqrt {static double erfensqrt (Double X) {If (x <0) {system. out. println ("no way to enable negative numbers"); 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 );}}

Test results:

1.732051134109497


5. calculation (INT) (SQRT (x) algorithm PS: this algorithm is not written by bloggers

Principle: Change the space time. For details, please explore the Code as follows:

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));}}

Test result: 8


6. Fastest SQRT algorithm PS: this algorithm is not written by bloggers

This algorithm is very famous, and you may have seen it. The author developed a game and SQRT is often used in graphics algorithms. The author wrote a God-Level Algorithm and his mysterious 0x5f3759df. The Code is as follows:

#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;}

Test results:


Interested friends can refer to http://wenku.baidu.com/view/a0174fa20029bd64783e2cc0.html
The author explains this algorithm's 14-page essay fast inverse square root


7. An algorithm similar to algorithm 6 Ps: this algorithm is not written by bloggers

The Code is as follows:

#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;}

Test results:





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

Author: Nash _ Welcome to repost. sharing with others is the source of progress!

Reprinted Please retain the original address: http://blog.csdn.net/nash_/article/details/8217866

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.