I dynamically fill an array of arguments and functions, where N + 1 is the number of equations, arguments:

a = [0]*(N+1) f = [0]*(N+1) i = 0 while i < (N + 1): a[i] = Symbol(('a'+chr(48+i))) f[i] = -R[i] i = i + 1 m = 0 while m < (N+1): i = 0 while i <= N - m: f[m] = f[m] + a[i]*a[i+m] i = i + 1 m = m + 1 print(f, a) 

shows:

 [a0**2 + a1**2 - 332.236351096697, a0*a1 - 106.241697077312] [a0, a1] 

I want to solve this system using nsolve:

 nsolve(f, a, [1]*(N+1)) 

I get the error:

 Traceback (most recent call last): File "C:/Users/Артем/PycharmProjects/tsp/tsp/tsp.py", line 158, in <module> print(ss_n(R[:2], 1)) File "C:/Users/Артем/PycharmProjects/tsp/tsp/tsp.py", line 118, in ss_n return nsolve(f, a, [1]*(N+1)) File "C:\Users\Артем\PycharmProjects\tsp\venv\lib\site-packages\sympy\utilities\decorator.py", line 91, in func_wrapper return func(*args, **kwargs) File "C:\Users\Артем\PycharmProjects\tsp\venv\lib\site-packages\sympy\solvers\solvers.py", line 2847, in nsolve x = findroot(f, x0, J=J, **kwargs) File "C:\Users\Артем\PycharmProjects\tsp\venv\lib\site-packages\mpmath\calculus\optimization.py", line 960, in findroot for x, error in iterations: File "C:\Users\Артем\PycharmProjects\tsp\venv\lib\site-packages\mpmath\calculus\optimization.py", line 658, in __iter__ s = self.ctx.lu_solve(Jx, fxn) File "C:\Users\Артем\PycharmProjects\tsp\venv\lib\site-packages\mpmath\matrices\linalg.py", line 227, in lu_solve A, p = ctx.LU_decomp(A) File "C:\Users\Артем\PycharmProjects\tsp\venv\lib\site-packages\mpmath\matrices\linalg.py", line 152, in LU_decomp raise ZeroDivisionError('matrix is numerically singular') ZeroDivisionError: matrix is numerically singular 

    1 answer 1

    For the given parameters, the solution results in a division by zero error ...

    With the "correct" parameters, everything works:

     In [107]: nsolve(funcs, (a0, a1), [1,0]) Out[107]: Matrix([ [17.1412006550957], [6.19803123567827]]) 

    To find all solutions, you can use solve :

     In [151]: solutions = solve(funcs, [a0, a1]) In [152]: solutions Out[152]: [(-17.1412006550957, -6.19803123567827), (-6.19803123567827, -17.1412006550957), (6.19803123567827, 17.1412006550957), (17.1412006550957, 6.19803123567827)] In [153]: nsolve(funcs, [a0, a1], solutions[0]) Out[153]: Matrix([ [-17.1412006550957], [-6.19803123567827]]) 
    • Do you know how to choose the optimal parameters? - j6wj1997
    • @ j6wj1997, give a definition for "optimal parameters". Are you trying to solve a system of nonlinear equations? If so, add to the question the equations themselves (in the form of equations) ... - MaxU
    • The equations are compiled depending on the parameter N, the more the more equations are compiled according to the text of the program - j6wj1997