这可以变得健壮吗?在不同的地方,我发现5 % 2 = 0和我以前从未遇到过这种“怪癖”,可能是因为对精度的无知:/
$checkPrimeCubeRoots = array(125, 124);
foreach ($checkPrimeCubeRoots as $int)
{
$cubeRoot = pow($int, 1/3); // double
// $int = 125, gives $cubeRoot = 5
// $int = 124, gives $cubeRoot = 4.986....
// some code that check for prime, but let's just check if divisble by 2
echo $cubeRoot % 2; // 0 -> yup 5 is divisible by 2
echo intval($cubeRoot) % 2; // 0 -> yup
// try round -> but gives false positive for 124
echo round ($cubeRoot) %2; // 1 -> nope, but in both cases :/
}发布于 2018-03-10 21:50:36
%仅用于整数。在浮点数上使用它的结果是有些不可预测的。尽管pow(125, 1/3)的结果看起来可能是一个整数,但它在内部是以浮点形式存储的(如果您想了解更多关于内部结构的信息,NikiC提供了一个有趣的article )。
一种快速的解决方案是使用fmod(),它是浮点版本。
echo fmod(pow(125, 1/3), 2); # 1
echo fmod(pow(124, 1/3), 2); # 0.98663095223865发布于 2018-03-10 21:50:51
当使用任何浮点/双精度类型的值时,可能会存储内部表示形式和实际值之间的一些细微差异。你也可以使用fmod(),它能更好地处理浮点数……
$checkPrimeCubeRoots = array(125, 124);
foreach ($checkPrimeCubeRoots as $int)
{
$cubeRoot = pow($int, 1/3); // double
// $int = 125, gives $cubeRoot = 5
// $int = 124, gives $cubeRoot = 4.986....
// some code that check for prime, but let's just check if divisble by 2
echo "%=".$cubeRoot % 2 .PHP_EOL;; // 0 -> yup 5 is divisible by 2
echo "intval=".intval($cubeRoot) % 2 .PHP_EOL;; // 0 -> yup
echo "fmod()=".fmod($cubeRoot,2).PHP_EOL;
// try round -> but gives false positive for 124
echo round ($cubeRoot) %2 .PHP_EOL; // 1 -> nope, but in both cases :/
}这就给了..。
%=0
intval=0
fmod()=1
1
%=0
intval=0
fmod()=0.98663095223865
1https://stackoverflow.com/questions/49209660
复制相似问题