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$
1
  • $\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$ Sep 20, 2015 at 16:06

1 Answer 1

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$
1
  • 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, 2015 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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