dpl22899 2013-02-26 11:38
浏览 152
已采纳

使用浮点数对多维数组进行排序

I have a multidimensional array with locations data (e.g. address, phone, name,..) and their relative distance from a certain point as floats (e.g. 0.49012608405149 or 0.72952439473047 or 1.4652101344361 or 13.476735354172).

Now I need to sort this array so that it starts with the data set of closest distance (0.49012608405149) and ends with the farthest (13.476735354172).

The function I use so far does a good job, but messes up some times, which is of course as it uses strcmp

function cmp($a, $b) {
            return strcmp($a["distance"], $b["distance"]);
        }
        usort($resultPartner, "cmp");

I googled a lot but couldn't find anything for my case. If possible I would like to avoid a foreach statement, as I read it can have a poor performance with big arrays.

Do you have any idea/experience with that and can give me a working function for this? Thank you!

  • 写回答

2条回答 默认 最新

  • douzhuoxia0587 2013-02-26 11:43
    关注

    strcmp() is binary safe string comparison why you don't just compare floats?

    When comparing floats php manual says

    Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

    So you must be careful.

    Look at this: http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm

    Since floating point calculations involve a bit of uncertainty we can try to allow for this by seeing if two numbers are ‘close’ to each other.

    Try something like this:

    function cmpfloat($a, $b) {
     if (abs($a["distance"]-$b["distance"]) < 0.00000001) {
       return 0; // almost equal
     } else if (($a["distance"]-$b["distance"]) < 0) {
       return -1;
     } else {
       return 1;
     }
    }
    

    Following function is good if comparing integer values:

    function cmp($a, $b) {
        return $a["distance"] < $b["distance"] ? -1 : ($a["distance"] === $b["distance"] ? 0 : 1);
    }
    

    if a distance is smaller than b distance return -1 if a distance equals b distance return 0 if a distance is greater than b distance return 1

    Reason: The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 eclipse连接sap后代码跑出来空白
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案