2017-03-03 43 views
0

第一篇文章,请温和。PHP - 以小的市场百分比改变价值

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

我想到了一个随机0,1遵循2 if语句1 rand(-0.01,0.05)如果2 rand(0.01,0.05)然后$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 
?> 
+1

你有错误?怎么了?请添加您的实际代码。 – chris85

+0

通常,您会“摆动”该值,然后检查它是否在范围内。即添加随机数,然后检查它是否低于10或高于75.这也取决于在发生这种情况时你会如何反应(应该什么也不做,或者将其限制在边界之内)。 –

+0

你可以复制粘贴代码,选择它并点击'{}'按钮,它将以可读的格式对其进行格式化:) – niceman

回答

0

兰德是整数(整数)

首先,你的两位小数值(称为浮动)之间兰特使用不会工作,因为兰特仅用于整数。所以,你首先要有一个随机函数做输出的花车,像这样:

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

然后我们就可以放心地使用它之间,也就是说,1%和5%:

$percentSwing = randomFloat(0.01, 0.05); 

兰德默认为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的范围。假设你想'钳'数字 - 这意味着如果它低于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; 

作为一个侧面说明在这里,真正的金融系统的钱ms从不存储为浮点数,因为rounding errors can cause major problems

+1

感谢您的帮助和详细的解释。 –