How to perform non-linear optimization with scipy/numpy or sympy?

前端 未结 4 1411
情书的邮戳
情书的邮戳 2021-02-06 07:23

I am trying to find the optimal solution to the follow system of equations in Python:

(x-x1)^2 + (y-y1)^2 - r1^2 = 0
(x-x2)^2 + (y-y2)^2 - r2^2 = 0
(x-x3)^2 + (y         


        
4条回答
  •  太阳男子
    2021-02-06 07:32

    I made an example script by the following. Note that the last line will find an optimal solution (a,b):

    import numpy as np
    import scipy as scp
    import sympy as smp
    from scipy.optimize import minimize
    
    a,b = smp.symbols('a b')
    x_ar, y_ar = np.random.random(3), np.random.random(3)
    x = np.array(smp.symbols('x0:%d'%np.shape(x_ar)[0]))
    y = np.array(smp.symbols('y0:%d'%np.shape(x_ar)[0]))
    func = np.sum(a**2+b**2-x*(a+b)+2*y)
    print func
    my_func = smp.lambdify((x,y), func)
    print 1.0/3*my_func(x_ar,y_ar)
    ab = smp.lambdify((a,b),my_func(x_ar,x_ar))
    print ab(1,2)
    
    def ab_v(x):
       return ab(*tuple(x))
    
    print ab_v((1,2))
    
    minimize(ab_v,(0.1,0.1))
    

    The outputs are :

    3*a**2 + 3*b**2 - x0*(a + b) - x1*(a + b) - x2*(a + b) + 2*y0 + 2*y1 + 2*y2
    1.0*a**2 - 0.739792011558683*a + 1.0*b**2 - 0.739792011558683*b    +0.67394435712335
    
    
    12.7806239653
    12.7806239653
    Out[33]:
      status: 0
     success: True
     njev: 3
     nfev: 12
     hess_inv: array([[1, 0],
       [0, 1]])
     fun: 3.6178137388030356
     x: array([ 0.36989601,  0.36989601])
     message: 'Optimization terminated successfully.'
     jac: array([  5.96046448e-08,   5.96046448e-08])
    

提交回复
热议问题