Ever wonder how the square-root button on your calculator works?

Nope, it's not the Underpants Gnomes. In this screencast we will demonstrate Newton's method of making a series of guesses, each one getting us closer to our answer.

we're gonna need an average function which will take x and y, add them together and divide that by 2.

now our newton function will take a guess in addition to our number that we want the square root of. It will divide our number by the guess and average that with the previous guess.

Let's try it on 81. Start with an initial guess of 1.0. We get 41.0. So we run it with that. And again, and again, until we start to converge on the answer. As we see, the square root of 81 is 9.

So now we can write a function to do that all for us.

We'll get the absolute value of a number, by taking its negation and seeing which one's bigger. 

To check the answer, we square it, or multiply it by itself.

We can now write our square root function. It will take an initial guess and a number. Make an if statement that will use our absolute value function to test whether we are within 0.0001 of our answer. If so return that value, otherwise we recursively call our newton function on it.

We can now call square root on the number 81 and we get 9.

Comments

Popular posts from this blog

MilkyTracker: The quest for the perfect music software

Programming: The New Rock 'N' Roll

Pardon My Parsing...