How to randomly sample from custom probability distributions

80 views
Skip to first unread message

Gary Bhumbra

unread,
Feb 18, 2021, 5:26:15 AM2/18/21
to sympy
I've looked in the SymPy documentation and cannot find a template for this. I apologise if I've overlooked something and the answer is trivial, but all I wish to do create a sampler for custom probability distributions defined using SymPy algebra e.g.:

from sympy.stats import ContinuousRV, sample
from sympy import sqrt, exp, Symbol, Interval, oo, pi
mean, prec = 1, 4
x = Symbol('x')
pdf = sqrt(prec)/sqrt(2*pi) * exp(-prec*(x-mean)**2/2)
Z = ContinuousRV(x, pdf, set=Interval(-oo, oo))
z = sample(Z)
print(next(z))


However the last line just produces a TypeError. I'd be grateful for any guidance!

Gary.

gu...@uwosh.edu

unread,
Feb 18, 2021, 8:53:19 AM2/18/21
to sympy
I think you have capital and little 'z' when you want only one. See the last three lines.

Gary Bhumbra

unread,
Feb 18, 2021, 9:10:02 AM2/18/21
to sympy
>   think you have capital and little 'z' when you want only one. See the last three lines.

Thanks for the suggestion. The original code (above) results in this error:

TypeError: 'Mul' object is not an iterator

If I try to follow your suggestion and modify the last three lines to:

Z = ContinuousRV(x, pdf, set=Interval(-oo, oo))
print(next(sample(Z)))

... I get the same error. I'm sorry if I'm misinterpreting your suggestion.

Gagandeep Singh (B17CS021)

unread,
Feb 18, 2021, 9:37:51 AM2/18/21
to sy...@googlegroups.com
Hi,

It seems like your code is working fine on SymPy's master branch.

Code

from sympy.stats import ContinuousRV, sample
from sympy import sqrt, exp, Symbol, Interval, oo, pi
mean, prec = 1, 4
x = Symbol('x')
pdf = sqrt(prec)/sqrt(2*pi) * exp(-prec*(x-mean)**2/2)
Z = ContinuousRV(x, pdf, set=Interval(-oo, oo))
z = sample(Z)
print(next(z))

Output

0.67209942564159



--
You received this message because you are subscribed to the Google Groups "sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/2ef6deab-d1cc-4c97-bd95-a73baff04336n%40googlegroups.com.


--
With regards,
Gagandeep Singh

Gary Bhumbra

unread,
Feb 18, 2021, 9:51:01 AM2/18/21
to sympy
Thanks Gagandeep,

Looks like my SymPy install was indeed old - happy to confirm that the code does work fine on SymPy version 1.7.1!

Kind regards,
Gary.
Reply all
Reply to author
Forward
0 new messages