2024 年日本 PHP 研討會

stats_rand_gen_normal

(PECL stats >= 1.0.0)

stats_rand_gen_normal從常態分佈產生單一隨機偏差值

描述

stats_rand_gen_normal(浮點數 $av, 浮點數 $sd): 浮點數

從平均值為 av、標準差為 sd 的常態分佈中返回一個隨機偏差值。

參數

av

常態分佈的平均值

sd

常態分佈的標準差

返回值

一個隨機偏差值

新增筆記

使用者貢獻的筆記 1 則筆記

KEINOS
4 年前
「stats_rand_gen_normal()」的替代方案。

<?php
/**
* 基於「Box–Muller 變換」的隨機偏差值產生器。
*
* @ref https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
*
* @param float|int $av 平均值
* @param float|int $sd 標準差
* @return float
*/
if (! function_exists('stats_rand_gen_normal')) {
function
stats_rand_gen_normal($av, $sd): float
{
$x = mt_rand() / mt_getrandmax();
$y = mt_rand() / mt_getrandmax();

return
sqrt(-2 * log($x)) * cos(2 * pi() * $y) * $sd + $av;
}
}
?>
To Top