finding least-squares integer solutions to a linear system with numpy/sympy

十年热恋 提交于 2019-12-10 19:13:23

问题


I need to solve a system of linear diophantine equations with either numpy or sympy.

Is there any way to constrain numpy's linalg.solve/linalg.lstsq method to return only integer solutions? (probably not but thought I should ask)

I looked into Sympy's diophantine solver and it does not seem to be applicable to solving whole systems

The problem I am working on is something along the lines of

P1(X) + P2(Y) = TargetPro
F1(X) + F2(Y) = TargetFat
C1(X) + C2(Y) = TargetCarb

In this case, X,Y,Z would represent the approximate serving sizes, and P1/F1/C1 would be the pro/fat/carb profile respectively.

based on this paper https://www.math.uwaterloo.ca/~wgilbert/Research/GilbertPathria.pdf

it seems as though I could conduct a row-reduction to find the ref of this system (row-echelon form) and then plug it into sympy's solver.

Is there an easier way to go about it?

Here's a trivial example:

pro = [4,5]
fat = [1,2]
carb = [3,6]

A = np.array((pro, fat, carb))
b = np.array([22,12,21])

print(np.linalg.lstsq(A, b))

I expected to get an integer solution [3,2] and instead got [ 2.16666667, 2.66666667]

Both solutions are correct, but I want to bound my solutions to only integer solutions

来源:https://stackoverflow.com/questions/37101110/finding-least-squares-integer-solutions-to-a-linear-system-with-numpy-sympy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!