1

I want to solve this system symbolically but it didn't work. where did I make the mistake? and how can I solve it?

import numpy as np
from sympy import symbols,Matrix
Y, C, I0, G0, a, b = symbols('Y, C, I_0, G_0, a, b')
npA = np.array(([1, -1], [-b, 1]))
npd = np.array((I0 + G0, a))
x = np.linalg.solve(npA, npd)
x

I get this error

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-42-7ec4f3174f18> in <module>
      5 npA = np.array(([1, -1], [-b, 1]))
      6 npd = np.array((I0 + G0, a))
----> 7 x = np.linalg.solve(npA, npd)
      8 x

<__array_function__ internals> in solve(*args, **kwargs)

~\anaconda3\lib\site-packages\numpy\linalg\linalg.py in solve(a, b)
    392     signature = 'DD->D' if isComplexType(t) else 'dd->d'
    393     extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
--> 394     r = gufunc(a, b, signature=signature, extobj=extobj)
    395 
    396     return wrap(r.astype(result_t, copy=False))

TypeError: No loop matching the specified signature and casting was found for ufunc solve1
Tatanik501
  • 159
  • 10

2 Answers2

1

You are attempting to solve such an equation: Ax = b. I don't think you can mix-up command from different libraries like that, there is some compatibility but you should check the documentation

Here a possibility

from sympy import symbols, Eq, solve

a_x, a_y, b_x, b_y = symbols('a_x, a_y, b_x, b_y')

eq_x = Eq(a_x - a_y, b_x)
eq_y = Eq(-b_x * a_x + a_y, b_y)

result = solve([eq_x, eq_y],(b_x, b_y))

print(result[b_x])
print(result[b_y])

Output

a_x - a_y
-a_x**2 + a_x*a_y + a_y
cards
  • 3,936
  • 1
  • 7
  • 25
  • and this worked for 2 equations but it didn't work for 4 equations? so is there something I need to add while solving more than equations or should I use something completely different? – Tatanik501 Aug 03 '21 at 11:19
  • It is ok. Sorry, I just need to specify the variables in the correct order. Thanks – Tatanik501 Aug 03 '21 at 11:31
1

If you need a more general setting (and more similar to a mathematical approach) then this can be useful

from sympy import symbols, Matrix, solve_linear_system

# a: parameter of the matrix
# b: inhomogeneity term

a, x_1, x_2, b_1, b_2 = symbols('b, x_1, x_2, b_1, b_2')

A = Matrix([[1, -1], [-a, 1]])
x = Matrix([[x_1, x_2]]).T
b = Matrix([[b_1, b_2]]).T

A_augmented = A.row_join(b)

result = solve_linear_system(A_augmented, *x)
print(result)

Output

{x_1: (-b_1 - b_2)/(b - 1), x_2: (-b*b_1 - b_2)/(b - 1)}

Remark

solve_linear_system take an augmented matrix as input [A|b] and you should either expand the unknown vectors (as above) or pass all its coordinates explicitly solve_linear_system(A_augmented, x_1, x_2)

cards
  • 3,936
  • 1
  • 7
  • 25