1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| import numpy as np from scipy.integrate import quad import matplotlib.pyplot as plt import sympy as sp
def f_X(x): return 1 if 0 <= x <= 1 else 0
def f_Y(y): return np.exp(-y) if y > 0 else 0
def f_Z(z): if z < 0: return 0 elif 0 <= z <= 2: integral, _ = quad(lambda y: f_Y(y), 0, z) return 0.5 * integral else: integral, _ = quad(lambda y: f_Y(y), z - 2, z) return 0.5 * integral
x, y, z = sp.symbols('x y z') pdf_x = sp.Piecewise((1, (x >= 0) & (x <= 1)), (0, True)) pdf_y = sp.Piecewise((sp.exp(-y), y > 0), (0, True))
convolution_expr = sp.integrate(pdf_x.subs(x, (z - y) / 2) * pdf_y, (y, 0, sp.oo))
latex_expr = sp.latex(convolution_expr)
print("LaTeX 表达式:", latex_expr)
z_values = np.linspace(0, 5, 500) pdf_values = [f_Z(z) for z in z_values]
plt.plot(z_values, pdf_values, label="PDF of Z = 2X + Y") plt.xlabel('z') plt.ylabel('f_Z(z)') plt.title('Probability Density Function of Z = 2X + Y')
plt.text(3.5, 0.15, f"${latex_expr}$", fontsize=12)
plt.legend() plt.grid(True) plt.show()
|