当符号被`subs`替换为值时,SymPy`solve`无法求解矩阵方程A * x = b

时间:2019-01-02 17:29:48

标签: python sympy linear-equation

我有一个要求解的线性方程,如Ax = b。我只想逐步显示符号并在末尾插入数字,并以数字显示问题的解决方案。我在插入数字时遇到问题。如果先前计算的值是整数,则一切正常。当我放入带有小数的东西时,它会打印

[]

这是简化的代码来说明我的问题:

Force = 100 #If I try to put in value of lets say 100.23 the problem happens
x_t = 15
L = 20
A, x, b = sym.symbols('A, x, b')
A_x, A_y, B_y = sym.symbols('A_x, A_y, B_y')
b, F, xt, l = sym.symbols('b, F, xt, L')

A = sym.Matrix([[1, 0, 0],
            [0, 1, 0],
            [0, 0, 1]])
b = sym.Matrix([[0],
            [F],
            [F*xt/l]])
x = sym.Matrix([[A_x],
            [A_y + B_y],
            [B_y]])

linear_eq = sym.Eq(A * x, b)
solution = sym.solve(linear_eq, x) #This always works fine(only symbols)
solution = sym.solve(linear_eq.subs( {F: Force, xt: x_t, l: L }), x )
solution

1 个答案:

答案 0 :(得分:1)

嗯,我不确定solve为何根本不起作用。不过,您可以使用https://vaadin.com/docs/v12/flow/advanced/tutorial-stream-resources.html。哪个也适用于F: 100.23

from sympy import *

A, x, b = symbols("A, x, b")
A_x, A_y, B_y = symbols("A_x, A_y, B_y")
b, F, x_t, L = symbols("b, F, x_t, L")

A = Matrix([
    [1, 0, 0],
    [0, 1, 0],
    [0, 0, 1]
])
x = Matrix([
    [A_x],
    [A_y + B_y],
    [B_y]
])
b = Matrix([
    [0],
    [F],
    [F * x_t / L]
])

solution = A.LUsolve(b.subs({
    F: 100.23,
    x_t: 15,
    L:20
}))
print(solution)

哪些印刷品:

Matrix([[0], [100.230000000000], [75.1725000000000]])