PHP - 以较小的市场百分比改变价值

PHP - Changing Value by a small market percentage

首先post,请轻柔

我正在尝试创建一个简单的市场脚本,例如我的数据库中有一个数字,即 50.00,我想 运行 一个 cron 作业 php 脚本来增加或减少这个随机到最低 10.00 和最高 75.00。

我认为随机 0,1 后跟 2 if 语句 1 rand(-0.01,0.05) if 2 rand(0.01,0.05) then $sql = "UPDATE price SET oil='RESULT'";

我已经在上面尝试了几次,但我无法将其设置为 运行 并且文件中的其他 crons 工作。

    <?php
//Get Oil Price from database
$oilchange = rand(1, 2);
if ($oilchange == '1') { 
  $oilnew = rand(0.01,0.05);
//Oil price from database times oil new.

} else { 
  $oilnew = rand(-0.01,-0.05);
//Oil price from database times oil new.
}
// Update Price
?>

兰特用于整数(整数)

首先,您在两个十进制值(称为浮点数)之间使用 rand 是行不通的,因为 rand 仅适用于整数。因此,您首先需要一个随机函数来输出浮点数,如下所示:

function randomFloat($min = 0, $max = 1) {
    return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}

然后我们可以安全地在 1% 和 5% 之间使用它:

$percentSwing = randomFloat(0.01, 0.05);

Rand 默认为 0 或 1。我们可以用它来随机反转它,所以我们也覆盖了 -1% 到 -5%:

$percentSwing *= rand() ? 1 : -1;

上面也可以这样写:

if(rand() == 1){
    // Do nothing:
    $percentSwing *= 1;
}else{
    // Invert it:
    $percentSwing *= -1;
}

所以,我们现在知道我们需要将数字调整多少。假设它是 $oilPrice:

$oilPrice = 48;

我们只需将波动百分比乘以该数字即可得到其变化量,然后将其加回去:

$oilPrice += $percentSwing * $oilPrice;

到目前为止一切顺利!现在我们需要确保价格没有超出 10 到 75 的固定范围。假设您想要 'clamp' 这个数字 - 这意味着如果它低于 10,则设置为 10,反之亦然,这样做是这样的:

if( $oilPrice < 10 ){
    // It went below 10 - clamp it:
    $oilPrice = 10;
}else if( $oilPrice > 75 ){
    // It went above 75 - clamp it:
    $oilPrice = 75;
}

以上也可以用一行表示,像这样:

$oilPrice = max(10, min(75, $oilPrice));

所以,这给了我们全部的东西:

function randomFloat($min = 0, $max = 1) {
    return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}

// Define the oil price (e.g. pull from your database):
$oilPrice = 48;

// get a random 1% to 5% swing: 
$percentSwing = randomFloat(0.01, 0.05);

// Invert it 50% of the time:
 $percentSwing *= rand() ? 1 : -1;

// Swing the price now:
$oilPrice += $percentSwing * $oilPrice;

// Clamp it:
$oilPrice = max(10, min(75, $oilPrice));

// Output something!
echo $oilPrice;

作为旁注,真实金融系统中的货币永远不会存储为浮点数,因为 rounding errors can cause major problems