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?
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.
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.
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.
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!