Dear Carlos,
unfortunately I can’t understand the cosine distribution in your source routine. Is there any reference what you want to code?
However, I can elaborate on how to sample from arbitrary 1D distribution.
Let’s try to sample the X random variable from the cos(x) function as a distribution.
f(x) \propto cos(x)
but we need to limit the value of X to
x \in \left[ -\frac{\pi}{2}, \frac{\pi}{2} \right]
because the probability can’t be negative, and Fortran uses radians.
First we need to calculate the Probability Density Function (PDF) f(x) of the distribution as such:
P(a \le X \le b) = \int_{a}^{b} f(x) dx
The integral of the PDF on the whole range of x, should be equal to 1.
P\left(-\frac{\pi}{2} \le X \le \frac{\pi}{2}\right) = \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} f(x) dx = \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} A \cdot cos(x) dx = 1
where A if the normalization factor. After doing the integration we get
A = \frac{1}{2}
So the PDF is
f(x) = \frac{1}{2} cos(x)
Now, we can write up the Cumulative Distribution Function (CDF) as the following:
F(x) = P(X \le x) = \int_{-\frac{\pi}{2}}^{x} f(x') dx' = \int_{-\frac{\pi}{2}}^{x} \frac{1}{2} cos(x') dx' = \frac{1}{2}\left(sin(x) +1 \right)
The value of the CDF is always between 0 and 1.
Then we can take the inverse function of the CDF, which is in this case:
F^{-1}(\xi) = asin(2\xi - 1)
Finally, we can sample \xi from an uniform distribution, where
\xi \in [0,1)
Doing so, the inverse CDF function will give us an x value according the f(x) distribution.
I implemented this in your source routine: basicsource.f (4.7 KB)
Since I wasn’t sure what you intended with the ini_ and fini_ variables, I used those to rescale the distribution, in such a way that the distribution ends at those values.
I hope this clarifies everything.
Cheers,
David