Ask Your Question
0

Create polynomial

asked 2016-02-01 21:55:06 +0100

Pro gravatar image

updated 2016-02-01 21:55:31 +0100

Hi all. I have a set od indexes of varibles and a need to create polynomial which can be evaluated from them. Example:

set = (2), (4), (5), (7,8)
polynomial = x2 + x4 + x5 + x7*x8

And I want to be able to evaluate it like this:

vector = (1, 0, 1, 0, 1, 0, 1, 0) 
result = polynomial(*vector)
# result = 0 + 0 + 1 + 1 * 0 = 1

Thank you

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2016-02-01 22:46:16 +0100

tmonteil gravatar image

I think that you missed some comas in your definition of set. Indeed, when you write, (2) you do not define the tuple with a single entry whose value is 2 but you define the integer 2:

sage: (2)
2

If you want to defint the tuple with a single entry whose valye is 2, you have to add a coma:

sage: (2,)
(2,)

So to be consistent with the tuple (7,8) i guess you wanted to write:

sage: set = (2,), (4,), (5,), (7,8)

Anyway, to define the polynomial you are expecting, you first have to define a polynomial ring with the wariables you want:

sage: R = PolynomialRing(ZZ,9,"x")
sage: R
Multivariate Polynomial Ring in x0, x1, x2, x3, x4, x5, x6, x7, x8 over Integer Ring

You can get the i^th variable as follows:

sage: R.gens()[4]
x4

Then, from the tuple of tuples set, you can easily make the sum of products as follows:

sage: polynomial = sum(prod(R.gens()[j] for j in i) for i in set)
sage: polynomial
x7*x8 + x2 + x4 + x5

For your second question (about evaluating), it works as you expect, with the following warning: in Sage as in Python, the indices start at 0, not at 1, so you should better do the following:

sage: vector = (0, 1, 0, 1, 0, 1, 0, 1, 0)  # see the 0 at the beginning, for the variable x_0
sage: polynomial(vector)
1
sage: vector = (0, 1, 3, 1, 0, 1, 0, 1, 0)
sage: polynomial(vector)
4
edit flag offensive delete link more

Comments

Thanks. Great

Pro gravatar imagePro ( 2016-02-04 17:01:43 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2016-02-01 21:55:06 +0100

Seen: 1,573 times

Last updated: Feb 01 '16