Reputation: 735
How can I make draws and obtain the CDF at certain values x
from a continuous triangular distribution with mode=0
, lower limit=-1
and upper limit=1
. I could not understand how to set the parameters. I want to get the equivalent of doing numpyp.random.triangular(left=-1, mode=0, right=1)
in Scipy
.
I attempted the following but I am not sure if that is what I am after.
scipy.stats.triang.cdf([-1,-0.5,0,0.5,1], c=0.5, loc=-1, scale=2)
and obtained: array([ 0, 0.125, 0.5, 0.875, 1.])
which seems correct.
I could not why
scipy.stats.triang.expect(func=lambda x: x, c = 0.5, loc=0.5, scale=1)
is producing error message
_argcheck() missing 1 required positional argument: 'c'
though the c
argument is provided.
Upvotes: 4
Views: 2823
Reputation: 114921
It looks like you got the parameters of the CDF function correct. In general, if you have left
, mode
and right
as used by numpy.random.triangular
, you can convert those to the parameters of scipy.stats.triang
using
c = (mode - left) / (right - left)
loc = left
scale = right - left
The arguments of the expect
method can be confusing. You tried this:
scipy.stats.triang.expect(func=lambda x: x, c = 0.5, loc=0.5, scale=1)
The correct call is
In [91]: triang.expect(lambda x: x, (0.5,), loc=0.5, scale=1)
Out[91]: 1.0
The second argument is a tuple that holds the shape parameters, which in this case is the tuple (c,)
. There isn't a separate keyword argument for the shape parameters.
To draw samples from a triangular distribution with width 2 centered at 0, use the rvs
method of scipy.triang
, with c=0.5
, loc=-1
, and scale=2
. For example, the following draws 10 samples:
In [96]: triang.rvs(c=0.5, loc=-1, scale=2, size=10)
Out[96]:
array([-0.61654942, 0.03949263, 0.44191603, -0.76464285, -0.5474533 ,
0.00343265, 0.222072 , -0.14161595, 0.46505966, -0.23557379])
Upvotes: 5