在浮点数列表中找到最接近的数字

本文关键字:最接近 数字 浮点数 列表 | 更新日期: 2023-09-27 18:17:45

你好,我有一个浮动列表

       List<float> distance = new List<float>();
        distance.Add(66.2F);
        distance.Add(69.9F);
        distance.Add(70.2F);
        distance.Add(70.3F);
        distance.Add(70.6F);
        distance.Add(71.4F);
        distance.Add(71.6F);

我有一个扩展方法,从这个数组中得到最接近的数字

 public static class extenstions
{
    public static float ClosestTo(this IEnumerable<float> collection, float target)
    {
        var closest = float.MaxValue;
        var minDifference = float.MaxValue;
        foreach (var element in collection)
        {
            var difference = Math.Abs((long)element - target);
            if (minDifference > difference)
            {
                minDifference = (int)difference;
                closest = element;
            }
        }
        return closest;
    }
}

float close = distance.ClosestTo(70F);现在,如果我想找到最接近的数字70,它将返回70.2,我想要修改这个函数,返回更接近的69.9,而不是更高的值70.2。你能帮忙吗?

在浮点数列表中找到最接近的数字

Using Linq:

public static float ClosestTo(this IEnumerable<float> collection, float target)
{
    return collection.OrderBy(x => Math.Abs(target - x)).First();
}

或者,使用Linq中的MinBy扩展方法。配件:

public static float ClosestTo(this IEnumerable<float> collection, float target)
{
    return collection.MinBy(x => Math.Abs(target - x));
}

它比使用OrderBy更好,因为它在O(n)而不是O(n log n)中运行。


编辑:如果两个数字同样接近目标,并且你想要两个数字中较大的那个,你可以这样做:

public static float ClosestTo(this IEnumerable<float> collection, float target)
{
    return collection
        .OrderBy(x => Math.Abs(target - x))
        .ThenByDescending(x => x)
        .First();
}

可能当你将value转换为long时,你会在昏迷70后丢失数字,2 -> 70和69,9 -> 69和70比69更接近70

如果你想取离左或右最近的值,使用:

    public static float ClosestTo(this IEnumerable<float> collection, float target)
    {
        float a = collection.Where(x => x >= target).OrderBy(x => x - target).First();
        float b = collection.Where(x => x < target).OrderBy(x => Math.Abs(target - x)).First();
        return a.Equals(b) ? a : Math.Min(a, b);
    }

其中a为右,b为左(如果你想左,将return a.Equals(b) ? a : Math.Min(a, b);改为return a.Equals(b) ? b : Math.Min(a, b);)

不要将元素变量强制转换为long。