Integrating a multidimensional integral in scipy

前端 未结 4 1255
故里飘歌
故里飘歌 2020-12-05 05:16

Motivation: I have a multidimensional integral, which for completeness I have reproduced below. It comes from the computation of the second virial coefficie

4条回答
  •  眼角桃花
    2020-12-05 05:56

    Jonathan Dursi has made a very good answer. I will just add on to his answer.

    Now scipy.integrate has a function named nquad that one can perform a multi-dimensional integral without hassle. See this link for more information. Below we compute the integral using nquad with Jonathan's example:

    from scipy import integrate
    import math
    import numpy as np
    
    def w(r, theta, phi, alpha, beta, gamma):
        return(-math.log(theta * beta))
    
    def integrand(r, theta, phi, alpha, beta, gamma):
        ww = w(r, theta, phi, alpha, beta, gamma)
        k = 1.
        T = 1.
        return (math.exp(-ww/(k*T)) - 1.)*r*r*math.sin(beta)*math.sin(theta)
    
    result, error = integrate.nquad(integrand, [[0, 1],             # r
                                                [0, 2 * math.pi],   # theta
                                                [0, math.pi],       # phi
                                                [0, 2 * math.pi],   # alpha
                                                [0, 2 * math.pi],   # beta
                                                [0, 2 * math.pi]])  # gamma
    expected = 16*math.pow(math.pi,5)/3
    diff = abs(result - expected)
    

    The result is more accurate than the chained tplquad:

    >>> print(diff)
    0.0
    

提交回复
热议问题