#Newton-Raphson for square root #Find x such that x**2 - 24 is within epsilon of 0 epsilon = 0.01 k = 24.0 guess = k/2 count = 0 while abs(guess*guess - k) >= epsilon: guess -= (((guess**2) - k)/(2*guess)) count += 1 print 'Newton-Raphson Method' print '-------------------------' print 'Guess number: ', count print 'Square root of', k, 'is about', guess #Bisection search for square root numGuesses = 0 low = 0.0 high = max(1, k) ans = (high + low) / 2.0 while abs(ans**2 - k) >= epsilon: numGuesses += 1 if ans**2 < k: low = ans else: high = ans ans = (high + low) / 2.0 print 'Bisection Method' print '--------------------------' print 'Guesses: ', numGuesses print 'Square root of', k, 'is about', ans
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question