带有 sympy 的条件期望 [英] Conditional expectation with sympy

查看:62
本文介绍了带有 sympy 的条件期望的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算 sympy 中随机变量的条件期望?我阅读了 this 并尝试:

from sympy.stats import *v = Uniform("v",0,1)E(v)

这会正确返回 1/2,但随后:

E(v, v>1/2)

返回 NaN.我也试过:

E(v, where(v > 1/2))

它返回了 1/2,这是不正确的(应该是 3/4).

我做错了什么?

解决方案

这个问题(我看到你了 已报告) 特定于均匀分布的随机变量.(还有一个涉及 Uniform 的旧问题.)对于其他发行版,您所做的工作有效正确:

<预><代码>>>>从 sympy.stats 导入 *>>>x = 指数("x", 1)>>>E(x, x <2)-3/(-1 + exp(2)) + exp(2)/(-1 + exp(2))

至于均匀类型,现在的解决方法是记住将均匀分布的随机变量调节到某个区间会创建另一个均匀分布的随机变量.

所以E(v, v > 1/2)的值可以通过计算得到

E(Uniform("x", 1/2, 1))

返回 0.75.

<小时>

注意:如果以交互方式工作,除了 stats 模块之外,您可能希望最终从核心 SymPy 导入.由于 E 在 SymPy 中代表欧拉数 2.718...,因此最终可能无法使用

计算期望值<块引用>

TypeError: 'Exp1' 对象不可调用

因此,要么必须更具体地了解要导入的内容,要么对一个或两个模块使用命名空间.我的首选解决方案是

from sympy import *将 sympy.stats 导入为 st

所以 st.E 是期望值,而 E 是 2.718...

How can I calculate the conditional expectation of a random variable in sympy? I read this and tried:

from sympy.stats import *
v = Uniform("v",0,1)
E(v)

this returns correctly 1/2, but then:

E(v, v>1/2)

returns NaN. I also tried:

E(v, where(v > 1/2))

it returned 1/2, which is incorrect (it should be 3/4).

What am I doing wrong?

解决方案

This issue (which I see you already reported) is specific to uniformly distributed random variables. (There's also an older issue involving Uniform.) For other distributions, what you did works correctly:

>>> from sympy.stats import *
>>> x = Exponential("x", 1)
>>> E(x, x < 2)
-3/(-1 + exp(2)) + exp(2)/(-1 + exp(2))

As for the uniform type, a workaround for now is to remember that conditioning a uniformly distributed random variable to some interval creates another uniformly distributed random variable.

So the value of E(v, v > 1/2) can be found by computing

E(Uniform("x", 1/2, 1))

which returns 0.75.


Caution: if working interactively, one may want to eventually import from core SymPy, in addition to its stats module. Since E stands for Euler's number 2.718... in SymPy, one may end up unable to compute expectations with

TypeError: 'Exp1' object is not callable

So one either has to be more specific about what to import, or use namespace for one or both modules. My preferred solution is

from sympy import *
import sympy.stats as st

So that st.E is expectation while E is 2.718...

这篇关于带有 sympy 的条件期望的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆