MIT Open course, Lecture 3 - Math problems

时间:2018-12-19 11:26:21

标签: python python-3.x xcode

I have a problem regarding the MIT OCW Python Lecture 3.

According to simple math, the code she uses shouldn't be succesful.

## EXAMPLE: approximate cube root 
####################
#cube = 27
##cube = 8120601
##cube = 10000
#epsilon = 0.1
#guess = 0.0
#increment = 0.01
#num_guesses = 0
## look for close enough answer and make sure
## didn't accidentally skip the close enough bound
#while abs(guess**3 - cube) >= epsilon and guess <= cube:
#    guess += increment
#    num_guesses += 1
#print('num_guesses =', num_guesses)
#if abs(guess**3 - cube) >= epsilon:
#    print('Failed on cube root of', cube, "with these parameters.")
#else:
#    print(guess, 'is close to the cube root of', cube)

This is the code she uses, the problem I'm having is understanding this part:

while abs(guess**3 - cube) >= epsilon and guess <= cube:
#    guess += increment

If guess is 0.0, cube is 27 and increment is 0.01 then the math by this term should be:

abs(0**3 - 27) = 27 #----- This is fine according to the code but the next step would be:#
abs(27.01**3 - 27) = 19677.878101

This should stop the loop from working any further. My understanding is obviously wrong somewhere but I can't see where!

Please halp...

1 个答案:

答案 0 :(得分:1)

您可以尝试使用Python可视化工具查看猜测值在每次迭代中如何变化。 Try here.