4
$\begingroup$

My problem is that Pick evaluates all the elements of a list at once. In my code I need a similar function that evaluates each element of a list. I need to generate 1000000 numbers for a PDF.

My code is:

n = 1000000;
yteste = RandomReal[{0, 2/3}, 2 n]; 
xteste = RandomReal[{-1, 1}, 2 n];

f[x_] := 2/3 (1 - Abs[x]^3)

If[Length[xaceitos] <= n, 
  AppendTo[xaceitos, Pick[xteste, UnitStep[f[xteste] - yteste], 1]], 
  Nothing]

Is there any other function that can do it?

$\endgroup$
  • $\begingroup$ Can you explain what you want your code to produce? What is the expected form of xaceitos, for instance? $\endgroup$ – J. M. will be back soon Sep 25 '18 at 18:42
  • $\begingroup$ I need to generate n numbers that follow the PDF f[x], this is the monte carlo Method. The problem is, when i use the rejection method i only receive less than n numbers. I need to receive exactly n numbers. $\endgroup$ – Hugo David Costa Pereira Sep 25 '18 at 18:45
  • 1
    $\begingroup$ That is slightly clearer, but only a little. So, you want to sample under the curve of f[x] for Abs[x] < 1? If so: dist = ProbabilityDistribution[f[x], {x, -1, 1}]; xaceitos = RandomVariate[dist, n]; Show[Histogram[xaceitos, Automatic, "PDF"], Plot[f[x], {x, -1, 1}]] $\endgroup$ – J. M. will be back soon Sep 25 '18 at 18:48
  • $\begingroup$ Yes, exactly. The curve of the histogram[xaceitos] must have the same shape o f[x]. $\endgroup$ – Hugo David Costa Pereira Sep 25 '18 at 18:50
7
$\begingroup$

As @JM says, just use ProbabilityDistribution:

dist = ProbabilityDistribution[f[x], {x, -1, 1}];

random = RandomVariate[dist, 10^6];
Length[random]

1000000

Visualization:

Histogram[random, Automatic, "PDF"]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.