用python符号表示的方程组



我想象征性地解决这个系统,但它不起作用。我哪里出错了?我该如何解决它呢?

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)
~anaconda3libsite-packagesnumpylinalglinalg.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)

相关内容

  • 没有找到相关文章

最新更新