dongshilve4392 2012-04-22 01:12
浏览 74
已采纳

intval(...)== floatval(...)在localhost上为FALSE,在实时PHP服务器上为TRUE

The following code is supposed to check to see if an inputed number is a power of 26. On the localhost the comparison evaluates as false when it should be true, but when it is running on the live php server it works as expected.

#there is an html text input
$foo = $_POST['someval'];

if(intval(log($foo, 26)) == floatval(log($foo, 26))) {
   echo 'yup, that there number is a power of 26';
}
else {
   echo 'nope, definitely not a power of 26';
}

I should note, on the localhost the "if" will SOMETIMES evaluate true. It happens for every other power of 26 (eg. 26 will be true, 676 (26 squared) will be false, 17576 (26 cubed) will be true). However when it is running on the live server, everything works as expected and the "if" evaluates true for every power of 26.

I can not figure out what is causing this discrepancy. The live server is running PHP 5.3.8 I have tried two different local stacks (mamp & ampps) which are running PHP 5.3.6 & 5.3.10 respectively and the same thing occurs on both.

I have also tried writing the code so that the math is done outside of the "if" statement with no luck there either.

This is not a high priority issue since the code works where it is supposed to (live) but it is bugging me that there is a discrepancy. Let me know if you see what is going on or if you have a better way to check if a number is a power of 26.

  • 写回答

1条回答 默认 最新

  • doupeng6890 2012-04-22 01:18
    关注

    Because of floating-point roundoff issues, and the lack of promise of exactness (log($foo, 26) is probably computed internally as log($foo)/log(26), which involves a floating point division) this doesn't sound like the kind of thing that you should count on working at all, let alone across different systems. I would suggest this instead:

    $foo == pow(26, (int)round(log($foo, 26)))
    

    which should always be exact as long as $foo fits within the PHP integer type to begin with. PHP's pow promises that the result will be an integer if both arguments are integer and if the result is within range of an integer. By finding the base-26 log of $foo, rounding it, and raising 26 to that power, this code basically finds the nearest power of 26 to $foo, and then that power can be compared directly to $foo to see if they're equal.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: