python 中的方程组符号化

System of equations in python symbolically

我想象征性地解决这个系统,但没有成功。我在哪里犯了错误?我该如何解决?

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

我收到这个错误

---------------------------------------------------------------------------
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

您正在尝试求解这样一个方程:Ax = b。我不认为你可以像那样混淆来自不同库的命令,有一些兼容性但你应该检查文档

这里有一个可能性

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])

输出

a_x - a_y
-a_x**2 + a_x*a_y + a_y

如果您需要更通用的设置(更类似于数学方法),那么这会很有用

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)

输出

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

备注

solve_linear_system 将增广矩阵作为输入 [A|b],您应该扩展未知向量(如上所述)或显式传递其所有坐标 solve_linear_system(A_augmented, x_1, x_2)