Lagrange: Solving Number Sequences

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) 

lagrange

That’s really simple right? You can try it with a more complicated example.

Hope it is useful

Talk Less Code More

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s