Optimizing gravitation calculation for particles in a zero gravity 2d space

前端 未结 5 942
北荒
北荒 2021-01-13 07:28

I\'ve have created a small visualisation of particles in python. I\'m caclulation the movement of particels in a 2D space with zero gravity. As each particle attracts all o

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 07:55

    to do fast calculation, you need to store x, y, speedx, speedy, m in numpy arrays. For example:

    import numpy as np
    
    p = np.array([
        (0,0),
        (1,0),
        (0,1),
        (1,1),
        (2,2),
    ], dtype = np.float)
    

    p is a 5x2 array which store x, y position of particles. To calculate the distance between each pair, you can use:

    print np.sqrt(np.sum((p[:, np.newaxis] - p[np.newaxis, :])**2, axis=-1))
    

    the output is:

    [[ 0.          1.          1.          1.41421356  2.82842712]
     [ 1.          0.          1.41421356  1.          2.23606798]
     [ 1.          1.41421356  0.          1.          2.23606798]
     [ 1.41421356  1.          1.          0.          1.41421356]
     [ 2.82842712  2.23606798  2.23606798  1.41421356  0.        ]]
    

    or you can use cdist from scipy:

    from scipy.spatial.distance import cdist
    print cdist(p, p)
    

提交回复
热议问题