function generate_attack_senquence($a,$b)
{
$a_count = $b_count = 0;
$a_rate = 1.0/$a;
$b_rate = 1.0/$b;
while(true)
{
$diff = ($a_rate + $a_count) - ($b_rate + $b_count);
if($diff < -1e-8)
{
print 'A ';
$a_count += $a_rate;
}
else if(-1e-8 <= $diff && 1e-8 >= $diff)
{
$a_count += $a_rate;
$b_count += $b_rate;
print 'A|B ';
}
else
{
$b_count += $b_rate;
print 'B ';
}
}
}
中间把-1e-8~1e-8之间的浮点值认为是0,因为程序中的浮点数的精度都是有限的。举个例子:
$onethird = 1.0/3;
$fivethirds = 1.0/3+1.0/3+1.0/3+1.0/3+1.0/3;
$half = 1.0/2;
$threehalf = 1.0/2+1.0/2+1.0/2;
var_dump($onethird + $fivethirds == $half + $threehalf);
上面这段程序将输出false,而实际上5/3+1/3=3/2+1/2=2。解决是:
var_dump(($onethird + $fivethirds) - ($half + $threehalf) > -1e-8 && ($onethird + $fivethirds) - ($half + $threehalf) < 1e-8);