Returns the square root using the BisectionMethod.

Source: Internet
Author: User
Returns the square root using the BisectionMethod. DefsqrtBI (x, epsilon): assertx & amp; gt; 0, Xmustbenon-nagtive, not + str .. use the Bisection Method to obtain the square root.

def sqrtBI(x, epsilon):    assert x>0, 'X must be non-nagtive, not ' + str(x)    assert epsilon > 0, 'epsilon must be postive, not ' + str(epsilon)      low = 0    high = x    guess = (low + high)/2.0    counter = 1    while (abs(guess ** 2 - x) > epsilon) and (counter <= 100):        if guess ** 2 < x:            low = guess        else :            high = guess        guess = (low + high)/2.0        counter += 1    return guess

Verify it.

>>> SqrtBI (2, 0.000001)

>>> 1.41421365738

The above method, if X <1, will have a problem. Because the square root of X (X <1) is not in the range of [0, x. For example, 0.25, the square root of which -- 0.5 is not in the range of [0, 0.25.

>>> SqrtBI (0.25, 0.000001)

>>> 0.25

Then how can we obtain the square root of 0.25?

You only need to slightly modify the above code. Pay attention to the code of lines 6 and 7.

def sqrtBI(x, epsilon):    assert x>0, 'X must be non-nagtive, not ' + str(x)    assert epsilon > 0, 'epsilon must be postive, not ' + str(epsilon)      low = 0    high = max(x, 1.0)    ## high = x    guess = (low + high)/2.0    counter = 1    while (abs(guess ** 2 - x) > epsilon) and (counter <= 100):        if guess ** 2 < x:            low = guess        else :            high = guess        guess = (low + high)/2.0        counter += 1    return guess

Verify:

>>> SqrtBI (0.25, 0.000001)

>>> 0.5

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.