Corresponding value of a parameter Hello, I am quite new to Sage and I have the following question. In my computations I have a quadratic form: $x^T A x = b$ , where the matrix A is defined already as a symmetric matrix, and x is defined as

import itertools
X = itertools.product([0,1], repeat = n)
for x in X:
x = vector(x)
print x

as all combination of $[0,1]$ repeated n times. I got a set of values for $b$ and extracted few of them from the set. Now, I need to identify which $x$ is corresponding to a particular value of $b$. Is there any command to do so? If it is possible. Thank you for help.

edit retag close merge delete

I don't understand two things. There is no variable x or b in your code. Furthermore, if you run this code what you get is an empty iterator W and a vector w equal to (1,1,...,1)

sage: import itertools
sage: W = itertools.product([0,1], repeat=4)
sage: for w in W: w = vector(w)
sage: W
<itertools.product object at 0x7f5c6f579410>
sage: list(W)
[]
sage: w
(1, 1, 1, 1)
sage: type(w)
<type 'sage.modules.vector_integer_dense.Vector_integer_dense'>

(note that you forgot the line import itertools in your command)

My apologies for ambiguity. I have edited the post. Hope it is now clearer.

the whole code with defined previously matrix A looks like this:

import numpy
import itertools
X = itertools.product([0,1], repeat = n)
results = []
for x in X:
x = vector(x)
x = x.row()
v = x.transpose()
b = x * A * v
results.append(b[0, 0])
print results

Sort by » oldest newest most voted

1) There is no need to import numpy that you are not using.

2) You can simplify

x = vector(x)
x = x.row()
v = x.transpose()
b = x * A * v

into

x = vector(x)
b = x * A * x

Now to answer your question. If you want to gather the images and the preimages you can use dictionaries. Let me consider the simpler example of the square function on Z/10Z.

sage: f = lambda x: x^2
sage: preimages = {}
sage: for x in Zmod(10):
....:     y = f(x)
....:     if y in preimages:
....:         preimages[y].append(x)
....:     else:
....:         preimages[y] = [x]
sage: preimages
{0: , 1: [1, 9], 4: [2, 8], 5: , 6: [4, 6], 9: [3, 7]}
sage: preimages
[2, 8]

And if you want to access the set of images (which is in my example the squares in Z/10Z)

sage: preimages.keys()
[0, 1, 4, 5, 6, 9]
more