# Given a value and conditions, find a matrix with that value as its determinant

I'm not sure if the title is named too obscurely, so I'll give an example of what I'm talking.

Say we have an integer matrix: M= 0 a b 0 (sorry for weird formatting; cannot seem to write matrices properly on here - any help with that as well? :P )

I want to find all values $(a,b) \in (-2,-1,0,1,2)$ such that $det(M)=2$.

I've tried the following but I'm not sure how to finish it off / if this is the right way to go:

    import itertools
for (a,b) in itertools.product([-2,-1,0,1,2], repeat=2):
M = Matrix(ZZ, [[0,a],[b,0]])
if M.determinant()==2:
min_params.append((a,b))
elif
min_params = [(a,b)]
print 'Sets of parameters with this determinant:', min_params


As I say, I feel like the start would be a good way to go, but I'm stuck when reaching elif, and I'm not sure if this is the right way to tackle this anyway!

Any help would be great!

edit retag close merge delete

Sort by ยป oldest newest most voted

This works for me :

import itertools
min_params=[] ## Do,'t forget to intitialize !
for (a,b) in itertools.product([u for u in (-2..2)], repeat=2):
M = Matrix(ZZ, [[0,a],[b,0]])
if M.determinant()==2: ## Mind the indentation : this is part of the loop...
min_params.append((a,b)) ## No need for an else clause
print 'Sets of parameters with this determinant:', min_params

Sets of parameters with this determinant: [(-2, 1), (-1, 2), (1, -2), (2, -1)]


You seem to struggle with the basics of the (admittedly peculiar) Python syntax, where (among others) whitespace is syntaxic...

I'd suggest to peruse a good Python tutorial ; keep in mind that Sage is currently Python2-based, but should soon (?) be Python3-based (and yes, there are a lot of devils in the seemingly small details...).

HTH,

more

Amazing, thank you!

I'm very much a novice in Sage and Python, and have yet to dedicate time to trying to learn it properly, instead opting to just piece things together as and when. Think it might be time for me to go to basics..

( 2019-02-21 07:16:28 -0500 )edit
1

May I recommend Computational Mathematics with SageMath as a study guide for Sage ? ISTR that it points you to satisfying Python tutorials when/where needed...

( 2019-02-21 10:16:06 -0500 )edit