Python Example--Babylon square root algorithm

Source: Internet
Author: User
Tags square root

The algorithm is as follows:

1. Guess the square root of a required number

2. Using the original number/guessing number

3. Use the value of the calculated step 2 and the average of the guessed number

4. Step 3 Gets the value for the new Guess value

5. Determine if the new guess value is the same as the original guess value, the same jump to step 2, the difference is that the guess value is the square root of the original number

# same as different in computer, reference floating point number same method

Python source code is as follows:


Import Math

From math import fabs

Num_be = input ("Please enter number with solve Square")

while (not Num_be.isdigit ()): #保证输入的为整数

Print ("Please enter Number")

Num_be = input ("Please enter number with solve Square")

Num_float = float (num_be)

Guess = input ("Please enter guess number")

while (not Guess.isdigit ()): #保证输入的为整数

Print ("Please enter Number")

Guess = input ("Please enter guess number")

Guess_float = float (guess)

Precision = float (input ("Please enter the precision")

Count = 0 #记录循环多少次

befor = 0 #前一个猜测值

Sum =0

while (Fabs (guess_float-befor) > Precision): #使用绝对值防止, where negative values are less than precision

befor = Guess_float

Guess_float = ((num_float/guess_float) + guess_float)/2

Count + = 1

Print ("Use Count:", count)

Print ("The", Num_float, "Square is:", guess_float)


Python Example--Babylon square root algorithm

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.