如何使用 SymPy 计算对数正态密度(从正态密度开始)

How to calculate the log-normal density (starting from the normal density) using SymPy

from sympy import *
x, y, mu, sigma, density1, density2 = symbols('x y mu sigma density1 density2')
eq1 = Eq(density1, 1/(sqrt(2*pi)*sigma)
                         *exp(-(x-mu)**2/(2*sigma**2)))     # normal 
eq2 = Eq(y, exp(x))                                         # substitution
eq3 = Eq(density2, 1/(y*sqrt(2*pi)*sigma)
                         *exp(-(ln(y)-mu)**2/(2*sigma**2))) # lognormal
[eq1, eq2, eq3]

输出:

如何让 SymPy 接受 normal density (eq1), apply the x to y substitution (eq2) and output the lognormal density (eq3)?

(我在 https://stats.stackexchange.com/q/55353/14202 没有收到这个问题的答案。)

当我们改变概率密度函数中的变量时,还需要将密度乘以执行替换的函数的导数。这就是代换在积分中的工作原理,概率密度必须有积分 1,所以我们必须尊重这一点。

让我们调用替换执行函数 f(在您的示例中为 log(y))。以下是该过程的工作原理,从您的设置开始:

f = solve(eq2, x)[0]
new_density = eq1.rhs.subs(x, f) * f.diff()
# test it now
Eq(new_density, eq3.rhs)  #  True