Points that follow a 1/R density distribution in an XY grid?

情到浓时终转凉″ 提交于 2019-12-23 05:23:38

问题


I have a XY grid with some gridpoints having certain values assigned to them, in this case, each value means a certain mass, so basically point masses in a grid. I now want to obtain a set of points which follow a density distribution of 1/R, where R is the distance from the center, so R = sqrt(x^2 + y^2). By density distribution, I mean the number of points has to fall off as 1/R. How would I go about coding this?

My code is below:

import numpy as np
x = np.linspace(-50,50,100)
y = np.linspace(-50,50,100)
X, Y = np.meshgrid(x,y)
zeta_a = (25,25)
zeta_b = (-10,5) 
M_a = 150
M_b = 150 

The zeta_a and zeta_b correspond to 2 point masses having masses of 150 units. I also need to perform follow up calculations using these points, so i'd also like to know how to use a more general format rather than using 'a','b','c' for n-point masses.

Thanks for your help.


回答1:


Assuming I understood your question (if not comments are welcomed):

The way to create any given distribution is by interpolating over the inverse of the distribution CDF. This is my function to do it:

import numpy as np
import matplotlib.pyplot as plt

def randdist(PDF, x, n):
    """Create a distribution following PDF(x). PDF and x
    must be of the same length. n is the number of samples."""
    fp = np.random.rand(n,)
    CDF = np.cumsum(PDF)
    return np.interp(fp, CDF, x)

Now, in your case we're going to work in polar coordinates with R distributed as 1/r and Theta uniformly distributed:

num = 1000   # The number of points
r = np.linspace(-50, 50, 100)
PDF = np.abs(1/r)
PDF = PDF/np.sum(PDF)    # PDF should be normalized
R = randdist(PDF, r, num)
Theta = 2*np.pi*np.random.rand(num,)

Now let's create the points x and y vectors

x = [R[k]*np.cos(Theta[k]) for k in range(num)]
y = [R[k]*np.sin(Theta[k]) for k in range(num)]

To plot

plot(x,y,'.')

Note that in my answer there is a hard cutoff at r=50. There are ways to overcome this but for now I leave it as it is.

Now you seem to also want to embed the points inside a 2D grid, much like a histogram. You can do that using

z, _, _ = np.histogram2d(x, y, [100, 100])


来源:https://stackoverflow.com/questions/38161872/points-that-follow-a-1-r-density-distribution-in-an-xy-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!