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

Question:

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?

Asked By: Austie Chou

||

Answers:

How about setting all values except m among the weights at random and finding only m based on those values?

Code:

import torch

N,d = 10, 10

# define X, W except m
X = torch.rand(N)
W = torch.rand(N-1)*4

# find m based on other weights
m = ((d - torch.dot(X[:N-1], W))/X[N-1]).unsqueeze(dim=0)
W = torch.cat((W, m))

print(X)
print(W)
print(torch.dot(X, W))

Result:

tensor([0.1062, 0.0361, 0.9462, 0.0534, 0.0591, 0.5729, 0.1521, 0.9087, 0.1210,
        0.7654])
tensor([2.3289, 0.4069, 3.8243, 2.2443, 1.1903, 0.6269, 0.2839, 3.9864, 0.4654,
        2.4148])
tensor(10.)
Answered By: core_not_dumped

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
Answered By: Austie Chou
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.