Introduction to computer science and programming (6) Improvement of the Bipartite method, Newton Iteration Method, array

Source: Internet
Author: User

1. Testing and improving procedures

In the fifth lecture, it has been implemented to solve the square root using the bipartite method. The Code is as follows:

def squareRootBi1(x,epsilon):    assert epsilon > 0,'epsilon must be postive,not' + str(epsilon)    low = 0    high = x    guess = (low + high)/2.0    ctr = 1    while abs(guess**2 -x) > epsilon and ctr <= 100:        if guess**2 < x:            low = guess        else:            high = guess        guess = (low +high)/2.0        ctr += 1    assert ctr <= 100,'Iteration count exceeded'    print('Bi method.Num.iterations:',ctr,'Estimate:',guess)    return guess

We can write test functions for some simple tests:

The test function can avoid repeated input.

# Test function: print ('squarerootbi1 (4, 0.0001) ') squareRootBi1 (4, 0.0001) print ('squarerootbi1 (9, 0.0001)') squareRootBi1 (9, 0.0001) print ('squarerootbi1 (2, 0.0001) ') squareRootBi1 (2, 0.0001) print ('squarerootbi1 (0.25, 0.0001)') squareRootBi1 (0.25, 0.0001)

After running, the result is as follows:

Traceback (most recent call last ):
File "<pyshell #63>", line 1, in <module>
TestBi1 ()
File "/Users/ihuangmx/Program/Python/Untitled. py", line 26, in testBi1
SquareRootBi1 (0.25, 0.0001)
File "/Users/ihuangmx/Program/Python/Untitled. py", line 14, in squareRootBi1
Assert ctr <= 100, 'iteration count exceeded'
AssertionError: Iteration count exceeded

The main cause of the error lies in the square root of test 0.25. According to common sense, the square root of 0.25 is 0.5, which has exceeded the range of 0.25, and the square of guess is certainly less than 0.25, therefore, guess will only keep approaching 0.25, but it will not exceed.

The solution is very simple, that is, when the square root number is less than 1, we should expand the range of the Bipartite to 1, that is, high = max (1, x)

# Finding the square root using the bipartite method # Improving the square root of the score def squareRootBi2 (x, epsilon): assert epsilon> 0, 'epsilon must be postive, not '+ str (epsilon) low = 0 high = max (1, x) # compared with the first version, the guess = (low + high) /2.0 ctr = 1 while abs (guess ** 2-x)> epsilon and ctr <= 100: if guess ** 2 <x: low = guess else: high = guess = (low + high)/2.0 ctr + = 1 assert ctr <= 100, 'iteration count exceeded' print ('bi method. num. iterations: ', ctr, 'estimate:', guess) return guess
2. Another Method for Finding the square root: Newton Iteration Method

When we are finding the square root (√ x = guess), we are actually finding the solution of guess 2-x = 0. For example, finding the square root of 16 is actually

Guess 2-16 = 0

This gives us a new inspiration for finding the square root: using the Newton Iteration Method to Solve the problem, for example, assuming that the initial guess value is 3, through the intersection of the tangent and the X axis, we can infer the next guess value, and the new guess value will get closer and closer to the desired solution. This is the basic principle of the Newton Iteration Method.

 

In fact, the Newton Iteration Method replaces the non-linear method. According to Taylor's formula:

Take the linear part (the first two items of Taylor's expansion) and make it equal to 0, that is

As an approximate solution of f (x) = 0.

Therefore, the formula of the Newton iteration method can be expressed:

According to this formula, the relationship between guessn + 1 and guessn can be expressed as follows:

Guessn + 1 = guessn-(guess 2-16)/2 guess

The specific code implementation is as follows:

# Using the Newton iteration method to obtain the square root def squareRootNR (x, epsilon): # Set the breakpoint assert x> = 0 for the values of x and epsilon, 'x must be non-negative, not '+ str (x) assert epsilon> 0, 'epsilon must be postive, not' + str (epsilon) guess = x/2.0 # The initial value of guess is set to x/2.0 diff = guess ** 2-x # The function value is stored in the diff variable ctr = 1 while abs (diff)> epsilon and ctr <= 100: guess = guess-diff/(2.0 * guess) diff = guess ** 2-x ctr + = 1 assert ctr <= 100, 'iteration count exceeded' print ('nr method. num. iterations: ', ctr, 'estimate:', guess) return guess

When the Newton Iteration Method itself fails, the approximate values will be repeated.

 

3. Comparison of efficiency between the bipartite method and the Newton Iteration Method

We can test the function to compare the efficiency of the two:

 

# Compare the efficiency def CprSquare (): print ('(2, 0.01)') squareRootBi2 (2, 0.01) squareRootNR (2, 0.01) print ('(2, 0.0001)') squareRootBi2 (2, 0.0001) squareRootNR (2, 0.0001) print ('(2, 0.000001)') squareRootBi2 (2, 0.000001) squareRootNR (2, 0.000001) print ('(123456789, 0.001)') squareRootBi2 (123456789, 0.0001) squareRootNR (123456789, 0.0001) print ('(123456789, 0.000001 )') squareRootBi2 (123456789, 0.000001) squareRootNR (123456789, 0.000001)

 

After running, it is shown as follows:

(2, 0.01)
Bi method. Num. iterations: Eight Estimate: 1.4140625
NR method. Num. iterations: 3 Estimate: 1.4166666666666667
(2, 0.0001)
Bi method. Num. iterations: 14 Estimate: 1.4141845703125
NR method. Num. iterations: 4 Estimate: 1.4142156862745099
(2, 0.000001)
Bi method. Num. iterations: 22 Estimate: 1.4142136573791504
NR method. Num. iterations: 5 Estimate: 1.4142135623746899
(123456789, 0.001)
Bi method. Num. iterations: 53 Estimate: 11111.111060553672
NR method. Num. iterations: 18 Estimate: 11111.111060555555
(123456789, 0.000001)
Bi method. Num. iterations: 59 Estimate: 11111.111060555599
NR method. Num. iterations: 18 Estimate: 11111.111060555555

It can be seen that with the expansion of the scale, the efficiency of the Newton Iteration Method is higher than that of the Bipartite method.

4. Array

To sum up the learned types, there are two basic types: integer and floating point. Not the basic type, you have learned the tuples and strings. One of the two types is immutable. Next we will learn a variable non-basic type: array.

 

# Create an array Techs = ['mit ', 'cal Tech'] print (Techs) # => ['mit ', 'cal Tech'] Ivys = ['Harvard ', 'yale', 'Brown '] print (Ivys) # => ['Harvard', 'yale', 'Brown '] # Use Univs for the append function = [] Univs. append (Techs) print (Univs) # => [['mit ', 'cal Tech'] Univs. append (Ivys) print (Univs) # => [['mit ', 'cal Tech'], ['Harvard ', 'yale ', 'Brown '] # traverse for e in Univs: print (e) for c in e: print (c) # computation Univs = Techs + Ivys # = ['mit ', 'cal Tech ', 'Harvard', 'yale ', 'Brown'] Ivys. remove ('Harvard ') # = "['yale', 'Brown '] Ivys [1] =-1 # =" ['yale',-1]

 

Next, we will continue to study arrays.

 

 

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.