简体   繁体   中英

Solving a multiple variable equation with python

I'm trying to create a program to solve this equation:

2.5 x + 3.5 y + 4.5 z + 5.5 t + 6.5 w + 10.5 f = d

I want to be able to set a value for d and get posite and whole numbers as a result for each variable.

import sympy as sp

import numpy as np


x, y, z, t, w, f = sp.var('x y z t w f', Naturals0=True, positive=True)

var = [x, y, z, t, w, f]

d = 14


Eqn = sp.Eq(2.5*x + 3.5*y + 4.5*z + 5.5*t + 6.5*w + 10.5*f, d)

for i in var:
    
    print(sp.solveset(Eqn, i, domain=sp.S.Naturals0))

I'm using the code above but I'm having 2 problems, first it give me back only the relative answers for each variable and I've not found a way to "control" the answer for being only positive and whole.

I know that maybe I get a lot of results depending on the number I set for d, but I need results in therms of numbers, nos equations.

Last but not least, I've already tried doing with numpy and matrix solving, but not suceeded.

Thanks in advance

When you want integer solutions for multiple variables in an equation you might be wanting to use diophantine ; solveset is more for solving for a single variable in terms of the others.

For diophantine give it the equation as an expression with integer coefficients:

>>> from sympy import Add, nsimplify, Eq, symbols, ordered
>>> s = d, f, t, w, x, y, z=symbols('d, f, t, w, x, y, z')
>>> e = Eq(2.5*x + 3.5*y + 4.5*z + 5.5*t + 6.5*w + 10.5*f, d)
>>> nsimplify(e.rewrite(Add), rational=True)
-d + 21*f/2 + 11*t/2 + 13*w/2 + 5*x/2 + 7*y/2 + 9*z/2
>>> eq = _

Now get an integer solution:

 >>> from sympy import diophantine
 >>> isol = diophantine(eq, syms=s); isol
 {(t_0, t_1, t_1 + t_2, t_1 + t_2 + t_3, t_1 + t_2 + t_3 + t_4,
 8*t_0 - 191*t_1 - 107*t_2 - 63*t_3 - 11*t_4 + 9*t_5,
 -6*t_0 + 143*t_1 + 80*t_2 + 47*t_3 + 8*t_4 - 7*t_5)}

This is a set of tuples (in this case 1) of either integers or variables representing integers that are a solution to the equation. In this case, 6 parameters are free to be chosen and then a particular solution can be found. We'll create a function f that can be used to see particular solutions easily:

>>> from sympy import Tuple, Dict, Lambda
>>> tsol = Tuple(*isol.pop())
>>> dsol = Dict(*zip(v, tsol))
>>> p = tuple(ordered(tsol.free_symbols))
>>> f = Lambda(p, dsol)

Now we can see a particular solution and see that it satisfies the original expression:

>>> f(1,2,3,4,5,6)
{d: 1, f: 2, t: 5, w: 9, x: 14, y: -948, z: 706}
>>> eq.subs(_)
0

So there are an infinite number of solutions governed by 6 arbitrary integers from which the other two are determined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM