Can we generate random numbers along the y-axis according to the bin content for a given value in the x-axis?

Dear experts,

I need to generate random numbers from a 2D histogram along the y-axis for a given value in the x-axis. The root has an option called “GetRandom2()”. But this function will return random numbers along the x and y axes according to bin content. Can we generate random numbers along the y-axis according to the bin content for a given value in the x-axis?

I appreciate your help.


ROOT Version: 6.24/08
ROOT Version: 6.28/10

Dear @rpradhan ,

Thank you for reaching out to the forum!

As a first approach, you could extract the histogram for the x-axis into a separate TH1D object using TH2::ProjectionX. From this object, you could use TH1::GetRandom to extract random values according the distribution of the x-axis and use those to fill the y-axis. I also invite @couet to the discussion who might have further suggestions.

Let us know if it helps,

I would suggest something similar as it looks like you are considering your 2D histogram more than a collection of 1d histograms than a real 2D histogram. May be @moneta has more idea. Also, looking at the GetRandom2 documentation, I noticed a typo. I make a PR to fix it: [skip-ci] Fix GetRandom2 doc by couet · Pull Request #14260 · root-project/root · GitHub . May be @vpadulan or @moneta can approve / merge it ?

I think that one of the ways to do what you wanna do is to slice the 2D histogram. You can create a 1D histogram (a slice) for the specific bin on the x-axis that you’re interested in. This 1D histogram will then reflect the y-axis distribution for that x-axis value. Once you have this 1D histogram, you can use the GetRandom() function to generate random numbers based on its bin contents.

This method allows you to focus solely on the y-axis distribution corresponding to a specific x-value. It requires a bit of additional coding, but it should give you the results you’re looking for.

Dear All,

Currently, I am doing what EmberEnigma said in the earlier email. I was wondering if we could do it directly from TH2D instead of taking projection to TH1D, input all the TH1D, read those, and then use GetRandom() to generate a random number.

Thank you for your help and time.


1 Like

Dear @rpradhan ,

The approach you suggest is currently not available in ROOT. Feel free to open a request for improvement at Sign in to GitHub · GitHub . Of course, if you feel like giving it a try yourself and propose a PR with the required changes, that would be extremely welcome!


This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.