如何使用SymPy和Python从连续函数中找到期望值?

huangapple go评论61阅读模式
英文:

How to find Expectation from continuous function with SymPy and Python?

问题

我想要根据 μ 和 X 计算期望和方差,但不知道如何填写下面的 X,因为它不是正态分布也不是泊松分布,而是一个随机的概率密度函数。

from sympy import symbols, Integral
from sympy.stats import Normal, Expectation, Variance, Probability

mu = symbols("μ", positive=True)

sigma = symbols("σ", positive=True)

pdf = (15/512)*(x**2)*((4-x)**2)
X = ?

print('Var(X) =', Variance(X).evaluate_integral())

print('E(X-μ) =', Expectation((X - mu)**2).expand())
print('final computation:')
print('E(X-μ) =', Expectation((X - mu)**2).doit())

另外,还有另一个条件 0 < x < 4。因此,E(X)=2 应该是正确的答案。

英文:

I want to calculate Expectation and Variance in terms of μ and X, but I do not know what to fill the X below, since it is not a Normal distribution nor Poisson, but a pdf that is random.

from sympy import symbols, Integral
from sympy.stats import Normal, Expectation, Variance, Probability

mu = symbols(&quot;μ&quot;, positive=True)

sigma = symbols(&quot;σ&quot;, positive=True)

pdf = (15/512)*(x**2)*((4-x)**2)
X = ?

print(&#39;Var(X) =&#39;,Variance(X).evaluate_integral())

print(&#39;E(X-μ) =&#39;,Expectation((X - mu)**2).expand())
print(&#39;final computation:&#39;)
print(&#39;E(X-μ) =&#39;,Expectation((X - mu)**2).doit())

In addition to that, there is another condition 0&lt;x&lt;4. Thus E(X)=2 should be the right answer.
如何使用SymPy和Python从连续函数中找到期望值?
Thanks.

答案1

得分: 1

或许你正在寻找ContinuousRV?

>>> from sympy.stats import ContinuousRV, P, E
>>> from sympy import Interval, Symbol
>>> from sympy.abc import x
>>> mu = Symbol('mu', positive=True)
>>> pdf = 15*x**2*(4 - x)**2/512
>>> X = ContinuousRV(x, pdf, Interval(0, 4))
>>> P(And(X>-1,X<1))
53/512
>>> E(X - mu)  # E(X) == Expectation(X).doit()
2 - mu
>>> E((X - mu)**2)
mu**2 - 4*mu + 32/7
英文:

Perhaps you are looking for ContinuousRV?

&gt;&gt;&gt; from sympy.stats import ContinuousRV, P, E
&gt;&gt;&gt; from sympy import Interval, Symbol
&gt;&gt;&gt; from sympy.abc import x
&gt;&gt;&gt; mu = Symbol(&#39;mu&#39;, positive=True)
&gt;&gt;&gt; pdf = 15*x**2*(4 - x)**2/512
&gt;&gt;&gt; X = ContinuousRV(x, pdf, Interval(0, 4))
&gt;&gt;&gt; P(And(X&gt;-1,X&lt;1))
53/512
&gt;&gt;&gt; E(X - mu)  # E(X) == Expectation(X).doit()
2 - mu
&gt;&gt;&gt; E((X - mu)**2)
mu**2 - 4*mu + 32/7

huangapple
  • 本文由 发表于 2023年2月24日 11:53:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552468.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定