在 python 中为给定的 PDf 生成 Rvs

计算科学 Python 统计数据 可能性
2021-12-08 05:23:21

两个随机变量 XY分布根据

fXY(x,y)={x+y0x1,0y10otherwise

我想使用 python 生成给定函数的 rvs。有什么办法吗?

1个回答

对于这种情况,拒绝抽样很容易实现。

import numpy as np


def rng_xpy(n, rng=None, chunk_size=1024):
    rng = np.random.default_rng(rng)
    rvs = []
    n_drawn = 0
    while n_drawn < n:
        # Draw numbers from U(0, 1) for x, y, and z
        # We draw numbers in chunks for efficiency
        x, y, z = rng.random((3, chunk_size))
        # Scale z to the maximum value of x+y
        z *= 2
        # We only want to use (x, y) values when z is less than x+y
        good_mask = z <= (x + y)
        xy = np.column_stack([x, y])[good_mask]
        rvs.append(xy)
        n_drawn += len(xy)
    # Because we draw in chunks, we probably drew too many.
    # Assemble the final array and trim it to the required number.
    xy = np.concatenate(rvs, axis=0)[:n]
    return xy