6
$\begingroup$

I don't understand why the following code

dis = ProbabilityDistribution[1/(x^2 + 1), {x, -5, 5}];
data = RandomVariate[dis, 10^4];;
Show[
 Histogram[data, 20, "ProbabilityDensity"],
 Plot[PDF[dis, x], {x, -5, 5}, PlotStyle -> Thick], 
 PlotRange -> {{-5, 5}, {0, 1}}]

Produces only negative data points? At the same time for the dis = NormalDistribution it works fine.

distribution picture

$\endgroup$
  • $\begingroup$ It would probably be more useful if you self-answer. The question's code is simple, and I bet many people would have this problem too. Self-answering is a practice that is encouraged on this site. $\endgroup$ – Leonid Shifrin Sep 20 '15 at 16:06
10
$\begingroup$

I understood it. The argument of the ProbabilityDistribution should be properly normalized. It would be actually useful if mathematica produced some kind of error message in this example. So the correct code should be:

norm = NIntegrate[1/(x^2 + 1), {x, -5, 5}];
dis = ProbabilityDistribution[(1/(x^2 + 1))/norm, {x, -5, 5}];
data = RandomVariate[dis, 10^4];
Show[
 Histogram[data, 20, "ProbabilityDensity"],
 Plot[PDF[dis, x], {x, -5, 5}, PlotStyle -> Thick], 
 PlotRange -> {{-5, 5}, {0, 0.4}}]
Export["c:/d/dist.png", %];

corrected picture

$\endgroup$
  • 6
    $\begingroup$ Note that in 10.2 and later you can do ProbabilityDistribution[1/(x^2 + 1), {x, -5, 5}, Method -> "Normalize"] and Mathematica will take care of the normalization for you. $\endgroup$ – Stefan R Sep 21 '15 at 19:23

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.