前言
在人生中我们会处处面临抉择,是选择A还是选择B呢。选对了可能皆大欢喜,选错了可能就是一个重要的转折点。
在刷知乎的过程中,经常会有类似的问题。看似荒诞的背后,却蕴藏着无限的哲学。
- 《每毫秒给你1个亿,代价是你每秒被动触发一次1亿分之一的死亡率,你愿意吗?》
- 《“100%概率获得200万”和“99%概率获得2个亿”,你选哪个?》
作为程序员,看着这种概率与决策,有时候常在想,我怎么做决策我的胜率概率最大,能不能用程序来模拟一下。我选择A赢的概率,我选择B赢的概率呢?
当然,必定是可以的,程序天然非常容易处理这些大数据,循环等问题,话不多说,直接看效果吧。
死亡概率模拟器
核心算法采用了“几何分布逆变换采样”
- O(1)时间复杂度,相比传统蒙特卡洛方法性能提升显著
- 数学准确性:基于几何分布的期望值 E[X] = 1/p
- 边界保护:处理 log(0) 等数学异常
- calculateDeathTime() {
- const p = this.selectedProbability.value;
- const u = Math.random();
- const u_safe = Math.max(u, 1e-10); // 避免log(0)
-
- // 几何分布公式:X = ceil(log(U) / log(1-p))
- const deathTime = Math.ceil(Math.log(u_safe) / Math.log(1 - p));
- return Math.max(1, deathTime);
- }
复制代码 风险抉择抽奖
采用了预计算 + 进度动画分离。
- 计算与渲染分离:避免10000次抽奖时的性能问题
- 固定时长体验:无论多少次抽奖,用户等待时间可控
- 平滑进度显示:50ms更新间隔保证流畅动画
[code]async startLottery() { // 步骤1:预先快速计算所有结果(无延迟) for (let i = 0; i < this.selectedTimes; i++) { const result = this.performSingleLottery(); this.results.push(result); } // 步骤2:根据次数设置固定动画时长 let animationDuration = 0; if (this.selectedTimes === 1) animationDuration = 0; // 立即 else if (this.selectedTimes === 10) animationDuration = 500; // 0.5s else if (this.selectedTimes === 100) animationDuration = 1000; // 1s else if (this.selectedTimes === 1000) animationDuration = 1500; // 1.5s else if (this.selectedTimes === 10000) animationDuration = 2000; // 2s // 步骤3:播放进度动画(仅更新显示) const updateInterval = 50; // 每50ms更新一次 const totalSteps = animationDuration / updateInterval; for (let step = 1; step |