首页 > 解决方案 > 当符号为实数时,SymPy 中的 nonlinsolve 给出虚解

问题描述

我的符号都被创建为实数(使用real=True)。如果我用它nonlinsolve来解决x_1^2+1我正确地没有得到任何解决方案。然而,更复杂的方程组会导致虚解。我误解了它的nonlinsolve工作原理吗?

# Create real symbols x_1,x_2,...,x_18
syms = [Symbol('x_{}'.format(i), real=True) for i in range(1,19)]
for i,s in enumerate(syms):
    exec('x_{} = syms[{}]'.format(i+1, i))

# This code respects the real attribute
test = [Eq(eq) for eq in [x_1*x_1+1]]
print(nonlinsolve(test, x_1))

# This code violates the real attribute and gives imaginary solutions
test = [Eq(eq) for eq in [36*x_1 + 15*x_18**3 - 50*x_18**2 + 6*x_18 - 4, 15*x_18**3 - 50*x_18**2 + 114*x_18 + 36*x_2 - 40, -15*x_18**3 + 50*x_18**2 - 54*x_18 + 12*x_3 + 28, x_4 + 1, -x_18 + x_5, x_6 - 1, -15*x_18**3 + 50*x_18**2 - 42*x_18 + 36*x_7 + 4, 15*x_18**3 - 50*x_18**2 + 6*x_18 + 36*x_8 - 4, 15*x_18**3 - 50*x_18**2 + 54*x_18 + 12*x_9 - 16, x_10 - 3*x_18 + 2, x_11 - 1, x_12 + x_18 - 1, 36*x_13 + 15*x_18**3 - 50*x_18**2 + 114*x_18 - 76, x_14 + 1, 18*x_15 - 15*x_18**3 + 50*x_18**2 - 24*x_18 + 4, 6*x_16 + 15*x_18**3 - 50*x_18**2 + 54*x_18 - 22, x_17 + 2*x_18 - 1, 15*x_18**4 - 20*x_18**3 + 14*x_18**2 + 8*x_18 - 8]]
print(nonlinsolve(test, syms))

标签: sympysolver

解决方案


记录nonlinsolve返回真实和复杂的解决方案: https ://docs.sympy.org/latest/modules/solvers/solveset.html#nonlinsolve

由于nonlinsolve它是新求解器的一部分,它使用集合工作,旨在忽略对输入符号的任何假设。通过与实数集相交,您只能得到实数解:

In [10]: nonlinsolve(test, syms) & Reals ** 18                                                                                    
Out[10]: 
⎧⎛2   √10  5   2⋅√10                √10       2   4⋅√10  2   √10                3⋅√10         √10  8   2⋅√10        4   √10     
⎨⎜─ - ───, ─ - ─────, -4 + √10, -1, ───, 1, - ─ + ─────, ─ - ───, 3 - √10, -2 + ─────, 1, 1 - ───, ─ - ─────, -1, - ─ + ───, 7 -
⎩⎝3    15  3     3                   5        3     15   3    15                  5            5   3     3          3    3      

            2⋅√10  √10⎞  ⎛√10   2  5   2⋅√10                -√10        4⋅√10   2  √10   2                3⋅√10     √10      2⋅√
 2⋅√10, 1 - ─────, ───⎟, ⎜─── + ─, ─ + ─────, -4 - √10, -1, ─────, 1, - ───── - ─, ─── + ─, 3 + √10, -2 - ─────, 1, ─── + 1, ───
              5     5 ⎠  ⎝ 15   3  3     3                    5           15    3   15   3                  5        5         3

10   8        4   √10                 2⋅√10  -√10 ⎞⎫
── + ─, -1, - ─ - ───, 2⋅√10 + 7, 1 + ─────, ─────⎟⎬
     3        3    3                    5      5  ⎠⎭

推荐阅读