简体   繁体   English

PHP in_array 似乎不起作用

[英]PHP in_array does not seem to work

i have two files: index.php and logspace.php.我有两个文件:index.php 和 logspace.php。 In logspace.php i have a function logspace that returns an array.在 logspace.php 我有一个返回数组的 function 日志空间。 I call this function from index.php.我从 index.php 中将其称为 function。 Then I want to check if this returned array has certain value but 'in_array' function doesn't work.然后我想检查这个返回的数组是否有一定的值,但 'in_array' function 不起作用。

Code in index.php: index.php 中的代码:

<?php
include 'logSpace.php';
$tmp=logspace(0.1,10,9);
$Tr=0.1;

if(in_array($Tr,$tmp))
{
    echo 'true';
}
else
{
    echo 'false';
}
?>

I always get 'false' even though value is clearly in the array:即使值显然在数组中,我总是得到“假”:

var_dumb($Tr); var_dumb($Tr);

float(0.1)

var_dump($tmp); var_dump($tmp);

array(10) { [0]=> float(0.1) [1]=> float(0.16681005372001) [2]=> float(0.27825594022071) [3]=> float(0.46415888336128) [4]=> float(0.77426368268113) [5]=> float(1.2915496650149) [6]=> float(2.1544346900319) [7]=> float(3.5938136638046) [8]=> float(5.9948425031894) [9]=> float(10) }

Code in logSpace.php logSpace.php 中的代码

function logspace($start,$end,$num)
{
    $arr=array();
    $logMin=log($start);
    $logMax=log($end);
    $delta=($logMax-$logMin)/$num;
    $accDelta=0;

    for($i=0;$i<=$num;$i++)
    {
        $num_i=pow(M_E,$logMin+$accDelta);
        $arr[]=$num_i;
        $accDelta+=$delta;
    }        
return $arr;
}
?>

in_array is going to be testing equality at some point, but your values are floating-point numbers. in_array将在某个时刻测试相等性,但你的值是浮点数。 Equality between floats in any computer language is touchy at best, because of limited precision. 由于精度有限,任何计算机语言中的浮点数之间的相等性最多都是敏感的。

1/10 in base-2 is classically compared to 1/3 in base-10. 基础-2中的1/10经典地比较基础10中的1/3。 You can't write 1/3 as a decimal using finite precision and be exact (0.3333...), and you have the same problem with 0.1 on a computer. 您不能使用有限精度将1/3作为小数写入并且精确(0.3333 ...),并且您在计算机上遇到0.1的相同问题。 The solution is either avoiding floats entirely (storing values as strings, storing integer multiples of your floats, calculating your float values on-the-fly, etc.), or sticking strictly to inequalities , rather than equality operations. 解决方案是完全避免浮动(将值存储为字符串,存储浮点数的整数倍,即时计算浮点数等),或严格遵守不等式 ,而不是等式运算。

For example: 例如:

$epsilon = 0.00001;
$target_num = 0.1;

foreach ($tmp as $flt)
{
    if ($flt - $epsilon < $target_num && $target_num < $flt + $epsilon)
    {
        return true; // ~0.1 is in $tmp
    }
}
return false; // ~0.1 is not in $tmp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM