[英]Why doesn't Sympy produce a numerical output?
I am using sympy to solve a system of equations Ax=B
and finding the matrix x
.我正在使用 sympy 求解方程组Ax=B
并找到矩阵x
。 x
is a 3 by 3 matrix, A
and B
are 3 by 4 matrices. x
是 3 x 3 矩阵, A
和B
是 3 x 4 矩阵。 The results are not numbers, but in the form of symbols.结果不是数字,而是符号的形式。 How can I obtain a numeric result?如何获得数字结果?
Code:代码:
import sympy as sp
X = sp.Matrix([[1,2,3,4],
[5,6,7,8],
[1,1,1,1]])
x = sp.Matrix([[5,6,7,8],
[1,2,3,4],
[1,1,1,1]])
a,b,c,d,e,f,g,h = sp.symbols('a,b,c,d,e,f,g,h')
M = sp.Matrix([[a,b,c],
[d,e,f],
[g,h,1]])
eq = solve(x-M.multiply(X),(a,b,c,d,e,f,g,h))
print(eq)
Output: Output:
{a: c/4, b: 1 - c/4, d: f/4 + 1, e: -f/4, g: 0, h: 0}
The output of solve
seems to indicate that there are infinity many solutions, and that you can use c
and f
as free parameters. solve
的 output 似乎表明有无穷多个解,并且可以使用c
和f
作为自由参数。 To see your full matrix, and choosing some values for c
and f
, you could use:要查看您的完整矩阵,并为c
和f
选择一些值,您可以使用:
M.subs(eq).subs({c:1, f:2}).evalf()
Result:结果:
Matrix([
[0.25, 0.75, 1.0],
[ 1.5, -0.5, 2.0],
[ 0, 0, 1.0]])
Here subs(eq)
fill in the solution.这里subs(eq)
填写解决方案。 subs({c:44, f:28})
fills in some values for c
and f
. subs({c:44, f:28})
填充c
和f
的一些值。 evalf()
creates a numerical result; evalf()
创建一个数值结果; this is needed when the expressions would contain fractions, square roots or other functions without evaluation.当表达式包含分数、平方根或其他没有求值的函数时,这是需要的。
For a more general approach, one could try to substitute all unassigned symbols with zero:对于更通用的方法,可以尝试用零替换所有未分配的符号:
Ms = M.subs(eq)
Ms.subs({fr:0 for fr in Ms.free_symbols}).evalf()
Result:结果:
Matrix([
[0, 1, 0],
[1, 0, 0],
[0, 0, 1]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.