I would like to compute square root using Taylor series. I’m just learning about the series and I wrote a bit of code but I don’t know why it doesn’t work, maybe I shouldn’t feed i to it? Please can anyone explain to me what I’m doing wrong?
I have the formula from http://en.wikipedia.org/wiki/Taylor_series#List_of_Maclaurin_series_of_some_common_functions
from math import sqrt
def factorial(n):
result = 1
for i in range(2, n+1):
result *= i
return result
def binomical(alpha, n):
result = 1
for i in range(0, n):
result *= (alpha - i)
return result / factorial(n)
for i in range(1, 10):
x = sum(binomical(0.5, k) * i ** k for k in range(10))
print x, sqrt(i)
There are two issues, one minor and one major. The minor is that the expansion is written in terms of
(1+x)^alpha, notx^alpha, so youri**kshould really be(i-1)**k. Doing this turns your output ofwhere you can see how suspiciously close your answer for
sqrt(1)is tosqrt(2)intowhich is much better. Unfortunately the remaining terms still aren’t very good:
and increasing the number of terms summed from 10 to 100 makes things even worse:
But that’s to be expected, because as the page you linked explains, this is only guaranteed to converge when the absolute value of x is less than 1. So we can do a good job of getting the roots of small numbers:
and we can try scaling things down to deal with other numbers:
or take the Taylor series around a different point, etc.
The general take-away is that Taylor series have a radius of convergence — possibly zero! — within which they give the right results. The Wikipedia Taylor series page has a section on “Approximation and convergence” which covers this.
(P.S. No “c” in “binomial”. :^)