Today’s article will discuss the “Lagrange: Solving Number Sequences”.
Suppose we have a sequence as follows:
1, 4, 9, 16, 25
And we want to know the next series without guessing. One way to do this is by using Lagrange polyomial.
Read more here.
Here’s how to overcome the problems with Lagrange series and its implementation with SageMath:
def tupleInList(fx, x=): for i in range(len(fx)): x.append(i+1) return zip(x, fx) def solve(s): return R.lagrange_polynomial(s) def nextSeq(l, f): exec('x = ' + str(l+1)) exec('f = ' + str(f).replace('^', '**')) return f if __name__ == '__main__': R = PolynomialRing(QQ, 'x') fx = [1, 4, 9, 16, 25] s = tupleInList(fx) print s f = solve(s) l = len(fx) print 'Formula: ', f print nextSeq(l, f)
That’s really simple right? You can try it with a more complicated example.
Hope it is useful
Talk Less Code More