using SciPy to integrate a function that returns a matrix or array

后端 未结 5 1552
野趣味
野趣味 2020-12-16 15:07

I have a symbolic array that can be expressed as:

from sympy import lambdify, Matrix

g_sympy = Matrix([[   x,  2*x,  3*x,  4*x,  5*x,  6*x,  7*x,  8*x,   9*         


        
5条回答
  •  感动是毒
    2020-12-16 15:58

    I might have found some interesting way of doing this, at the expense of defining different symbols for the matrix g_symp:

    import numpy as np
    from scipy.integrate import quad
    import sympy as sy
    
    @np.vectorize
    def vec_lambdify(var, expr, *args, **kw):
        return sy.lambdify(var, expr, *args, **kw)
    
    @np.vectorize
    def vec_quad(f, a, b, *args, **kw):
        return quad(f, a, b, *args, **kw)[0]
    
    Y = sy.symbols("y1:11")
    x = sy.symbols("x")
    mul_x = [y.subs(y,x*(i+1)) for (i,y) in enumerate(Y)]
    pow_x = [y.subs(y,x**(i+1)) for (i,y) in enumerate(Y)]
    
    g_sympy = np.array(mul_x + pow_x).reshape((2,10))
    X = x*np.ones_like(g_sympy)
    G = vec_lambdify(X, g_sympy)
    I = vec_quad(G, 0, 100)
    print(I)
    

    with results:

    [[  5.00000000e+03   1.00000000e+04   1.50000000e+04   2.00000000e+04
        2.50000000e+04   3.00000000e+04   3.50000000e+04   4.00000000e+04
        4.50000000e+04   5.00000000e+04]
    [  5.00000000e+03   3.33333333e+05   2.50000000e+07   2.00000000e+09
       1.66666667e+11   1.42857143e+13   1.25000000e+15   1.11111111e+17
       1.00000000e+19   9.09090909e+20]]
    

    and using the ipython magic%timeit vec_quad(G,0,100) I got

    1000 loops, best of 3: 527 µs per loop
    

    I think this approach is somewhat more clean, despite the juggling with symbols.

提交回复
热议问题