I'm trying to solve an overdetermined linear system of equations with numpy. Currently, I'm doing something like this (as a simple example):
a = np.array([[1,0], [0,1], [-1,1]])
b = np.array([1,1,0])
print np.linalg.lstsq(a,b)[0]
[ 1. 1.]
This works, but uses floats. Is there any way to solve the system over integers only? I've tried something along the lines of
print map(int, np.linalg.lstsq(a,b)[0])
[0, 1]
in order to convert the solution to an array of ints, expecting [1, 1]
, but clearly I'm missing something. Could anyone point me in the right direction?
You should use specialized integer problem solvers (note that integer problems are not even simple to solve).
openopt
is a package that for example should provide good wrappers for integer quadratic optimization such as you are doing. Trying to use linear algebra will simply not give you the correct solution that directly.Your problem can be written as with a quadratic program, but it is an integer one, so use
openopt
or some other module for that. Since it is a very simple, unconstrained one, maybe there is some other approach. But for starters it is not the simple problem it looks like at first, and there are programs in openopt, etc. ready to solve this kind of thing efficiently.When you convert to
int
, the decimal part of the elements gets truncated, so it is rounded down.Result:
There is a method called block lanczos. This can your answer over a finite field. There are block lanczos solvers you find for this specific problem.
You are looking at a system of linear diophantine equations. A quick Google search comes up with Systems of Linear Diophantine Equations by Felix Lazebnik. In that paper, the author considers the following question:
+1 to seberg, here is a counter example to illustrate that you should not map round:
(Sorry, it's matlab style, but you'll easily pythonize)
I may be misunderstanding your problem, but I think you just need a combination of
round
and thenastype(int)
?E.g.