Search code examples
pythonnumpypytorch

find N solutions for aX1+bX2+cX3+.....mXn=d, Python


How can I find any N(like 30) solutions for aX1+bX2+cX3+.....mXn=d,(where n, also known as dimension of this space, could be a int larger than 2, and 0<=Xn<=1.)

weights = torch.tensor([a,b,c....m])
# X is a  tensor with the same size of w
# What I want do is to find a tensor X that qualified for:
(weights*X).sum() = d

when dimension is 2, I randomly generate a tensor like this:

u = 0.5
t = torch.rand(2)
if t*weights == d:
   return t 

This method gets extremely slow when dimension gose larger than 2. Any better solutions to solve this?


Solution

  • I've found a simple solution using linear algebra my self. The solution fits in space [0,1]^N

    class A:
        def __init__(dim,weights):
            self.dim = dim
            self.weights = weights
    
    
        def gen_solution(self)->torch.Tensor:
            w = self.weights
            s = self.target
    
            v = torch.rand(self.dim)
            v = v -(w*v).sum() * w / (w **2).sum()
            vmin = v.min()
            if vmin < -s:
                v = v * s / (-vmin)
            vmax = v.max()
            if vmax > (1-s):
                v = v * (1-s) / vmax
            solution =  v + s
            return solution