Last Night while sitting in a math class I listened as the Professor explained Newton's Method. Basically it is a method to improve an estimate of where a function has a zero, meaning for what value of x will y be zero. He then showed how to use this information to calculate the square root of three.
For the last little bit, I have been reading a book on Python programming that I bought last December. Learning a new language is not a spectators sport. Reading alone does not cut it.
When I got home last night, I took my new found information and implemented a square root function in p\Python. This is my first real program in Python. It is a pretty simple actually, though pretty useless because Python's math module already implements a square root function, math.sqrt(). I tested my function against the library function. Mine gave the same result to the same number of digits for every value I tested.
def squareRoot(square):
'''calculate the square root of a number'''
def f(x):
return (x*x) - square
def fp(x):
return (2*x)
def newtonsMethod(x):
return x - ( f(x) / fp(x) )
input = float(square) / 2
for i in range(1, 10):
output = newtonsMethod(input)
if output == input: break
input = output;
return output
It's got some spam in it.
Want a cube root function? Just ask.
Newtons Method says for some value X0 plugged into his formula, it will produce an X1 which is a more accurate solution. After a few iterations you have a value accurate to a dozen digits.
NM:
X1 = X0 - ( f(x0) / fp(x0) )
where f(x) is the function of the equation you are estimating and fp(x) is the first derivative of f(x).
So to find the cube root, replace f(x) with
f(x) = x**3 - cube
and the first derivative would be
fp(x) = 3 * x**2
Apply Newton's method for a few iterations and you have an answer.
If your interested in learning a new programming language, give Python a try. It's free and there are lots of resources available. Check it out at www.python.org
Spam, Spam, Spam, Spam, Spam, Spam, eggs, and Spam.
1 comment:
I prefer Bacon with my eggs.
Are you doing your homework on your blog???? I need a translator please.
Post a Comment