Search code examples
pythonmathrandomgeometryellipse

How to generate a random sample of points from a 3-D ellipsoid using Python?


I am trying to sample around 1000 points from a 3-D ellipsoid, uniformly. Is there some way to code it such that we can get points starting from the equation of the ellipsoid?

I want points on the surface of the ellipsoid.


Solution

  • Here is a generic function to pick a random point on a surface of a sphere, spheroid or any triaxial ellipsoid with a, b and c parameters. Note that generating angles directly will not provide uniform distribution and will cause excessive population of points along z direction. Instead, phi is obtained as an inverse of randomly generated cos(phi).

        import numpy as np
        def random_point_ellipsoid(a,b,c):
            u = np.random.rand()
            v = np.random.rand()
            theta = u * 2.0 * np.pi
            phi = np.arccos(2.0 * v - 1.0)
            sinTheta = np.sin(theta);
            cosTheta = np.cos(theta);
            sinPhi = np.sin(phi);
            cosPhi = np.cos(phi);
            rx = a * sinPhi * cosTheta;
            ry = b * sinPhi * sinTheta;
            rz = c * cosPhi;
            return rx, ry, rz
    

    This function is adopted from this post: https://karthikkaranth.me/blog/generating-random-points-in-a-sphere/