# The realization of the calculation function of sqrt () square root----two-point method

Source: Internet
Author: User

C Language Standard library:

http://www.cplusplus.com/reference/cmath/

In an interval, each time the square of the middle number to test, if large, then try the middle of the left interval, if it is small, then take the middle of the right interval to try. For example sqrt (16) results, you first try (0+16)/2=8,8*8=64,64 than 16, then move to the left, try (0+8)/2=4,4*4=16 just, got the correct result sqrt (16) = 4.

Implementation of the first time I did not carry out precision control, resulting in some can not complete the root of the number of operations, but also forget the judgment of non-integers. Code 1 for the corrected code, followed by code 2 for the first write code, posted here for comparison reminders.

Code Listing 1:

ESP is often used in C + + to control iterative precision, which is a constant declared by a function program, and is an infinitely small value in calculus.

float esp=0.000000;

Double sqrt (double x)

{

Double down,up,n,last;

down=0;

Up=x;

n= (Down+up)/2;

if (x<=0)

return x;

while ((n*n!=x) &&abs (last-n) >esp)

{

if (n*n<x)

{

Down=n;

Last=n;

n= (Down+up)/2;

}

Else

{

Up=n;

Last=n;

n= (Down+up)/2;

}

}

return n;

}

Code Listing 2:

Double sqrt (double x)

{

Double down,up,n;

down=0;

Up=x;

n= (Down+up)/2;

while (N*N!=X)

{

if (n*n<x)

{

Down=n;

n= (Down+up)/2;

}

Else

{

Up=n;

n= (Down+up)/2;

}

}

return n;

}

Reference: http://www.2cto.com/kf/201206/137256.html

The realization of the calculation function of sqrt () square root----two-point method

Related Keywords:

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.