Home > Mobile >  Numpy to solve multi-variable algebraic function
Numpy to solve multi-variable algebraic function

Time:07-22

Let's assume we know the following:

a = 1
b = 4
c = 7
d = 2
e = 2
f = 9

With these six variables, we can solve for X, Y, and Z as follows:

X = (b - a) / (d   e)
Y = 2 * np.sin(X/2) * ((c / X)   f)
Z = 2 * np.sin(X/2) * ((a / X)   d)

print(X)
print(Y)
print(Z)
0.75
13.42999273315508
2.4418168605736503

Now, let's flip things around and assume that we're given the values of X, Y, and Z, as well as d, e, and f.

How would we solve for the values of a, b, and c? My algebra is shaky. Is this something that Numpy can handle?

Thanks!

CodePudding user response:

Numpy, no. (Or rather, not as easily, or accurately.)

Sympy, yes.

Declare a, b and c as symbols. Create expressions that should equal to zero (by moving the left hand side of the equation to the right hand side and changing the sign). Use sympy.sin instead of math.sin or np.sin. Use sympy.solve to get the solution of the system.

import sympy
from sympy.abc import a, b, c

X = 0.75
Y = 13.42999273315508
Z = 2.4418168605736503
d = 2
e = 2
f = 9

e1 = (b - a) / (d   e) - X
e2 = 2 * sympy.sin(X/2) * ((c / X)   f) - Y
e3 = 2 * sympy.sin(X/2) * ((a / X)   d) - Z

sympy.solve([e1, e2, e3])
# => {a: 1.00000000000000, b: 4.00000000000000, c: 7.00000000000000}

CodePudding user response:

Solving equations with unknown variables can be done in Sympy.

from sympy import symbols, solve, Eq, sin

a, b, c, d, e, f, X, Y, Z = symbols("a b c d e f X Y Z")

eqns = [
    Eq(X, (b - a) / (d   e)),
    Eq(Y, 2 * sin(X / 2) * ((c / X)   f)),
    Eq(Z, 2 * sin(X / 2) * ((a / X)   d)),
]
assignments = {a: 1, b: 4, c: 7, d: 2, e: 2, f: 9}

print(solve([eq.subs(assignments) for eq in eqns], [X, Y, Z]))

Output:

[(3/4, 110*sin(3/8)/3, 20*sin(3/8)/3)]

To solve for a, b, c just replace X, Y, Z in solve and add their values in the assignments dict.

  • Related