You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

可变抽取率下随机过程模拟:如何维持事件频率稳定?

固定事件频率的可变抽取率实现方案

你的核心需求是让事件发生的长期平均频率保持稳定,不受抽取频率波动的影响。原代码的问题在于,每次抽取都用「上次事件发生到现在的总时长」计算触发概率,当抽取变频繁时,多次独立判断会让实际触发概率被叠加放大,导致事件频率升高。

核心思路

要实现稳定的事件频率,我们需要基于两次抽取之间的时间间隔来计算本次抽取的事件触发概率,而不是从上次事件到现在的总时长。本质是维护一个「未触发事件的累积概率」,每次抽取时只计算这段间隔内的事件风险增量,这样无论抽取多频繁,长期来看事件的平均频率都会稳定在目标值。

修正后的代码

import time
import numpy as np
import matplotlib.pyplot as plt

target_rate = 1.0  # 目标事件频率(次/秒)
last_event_time = time.time()
last_sample_time = time.time()  # 记录上次抽取的时间
event_intervals = []
event_timestamps = []  # 记录事件发生的绝对时间,方便观察频率
count = 0

# 累积未触发事件的概率初始值为1(还未经过任何时间)
survival_prob = 1.0

while count < 10:
    # 随机抽取间隔
    time.sleep(np.random.rand() / 100)
    current_time = time.time()
    
    # 计算两次抽取之间的时间间隔Δt
    delta_t = current_time - last_sample_time
    last_sample_time = current_time
    
    # 更新累积未触发概率:经过Δt时间后,未触发事件的概率
    survival_prob *= np.exp(-target_rate * delta_t)
    
    # 本次抽取的事件触发概率 = 1 - 当前累积未触发概率
    trigger_prob = 1 - survival_prob
    
    if np.random.rand() < trigger_prob:
        # 事件触发,记录相关信息
        event_intervals.append(current_time - last_event_time)
        event_timestamps.append(current_time)
        last_event_time = current_time
        count += 1
        # 重置累积未触发概率
        survival_prob = 1.0

# 可视化事件间隔和时间分布
plt.figure(figsize=(12, 5))
plt.subplot(121)
plt.plot(event_intervals, np.ones_like(event_intervals), 'ro')
plt.title('事件间隔')
plt.xlabel('间隔时长(秒)')

plt.subplot(122)
plt.plot(event_timestamps, range(1, count+1), 'b-')
plt.title('事件累积数量')
plt.xlabel('时间(秒)')
plt.ylabel('事件数')

plt.tight_layout()
plt.show()

关键改动说明

  • 新增last_sample_time:跟踪每次抽取的时间,计算两次抽取的时间差delta_t,而非从上次事件到现在的总时长。
  • 累积survival_prob:表示从上次事件后,到当前抽取时还未触发事件的概率,每次用delta_t更新这个值。
  • 触发概率计算:每次抽取的触发概率是1 - survival_prob,代表从上次事件后到当前时刻,事件应该发生的概率增量。
  • 事件触发后重置:事件发生时,重置累积概率和事件时间戳,开始下一轮的计算。

这样实现后,无论抽取频率如何变化,事件的长期平均频率都会稳定在target_rate设定的值(比如示例中的1次/秒),不会因为抽取变频繁而升高。

内容的提问来源于stack exchange,提问作者FilterFeeder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 16:07:25