C++ 如何将浮点数初始化为其最大值/最小值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2684603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:21:12  来源:igfitidea点击:

how do I initialize a float to its max/min value?

c++primitive-types

提问by Faken

How do I hard code an absolute maximum or minimum value for a float or double? I want to search out the max/min of an array by simply iterating through and catching the largest.

如何硬编码浮点数或双精度数的绝对最大值或最小值?我想通过简单地迭代并捕获最大的来搜索数组的最大值/最小值。

There are also positive and negative infinity for floats, should I use those instead? If so, how do I denote that in my code?

浮点数也有正无穷大和负无穷大,我应该使用它们吗?如果是这样,我如何在我的代码中表示?

回答by Yacoby

You can use std::numeric_limitswhich is defined in <limits>to find the minimum or maximum value of types (As long as a specialization exists for the type). You can also use it to retrieve infinity (and put a -in front for negative infinity).

您可以使用std::numeric_limits其中定义的 which<limits>来查找类型的最小值或最大值(只要该类型存在特化)。您还可以使用它来检索无穷大(并-在前面放置负无穷大)。

#include <limits>

//...

std::numeric_limits<float>::max();
std::numeric_limits<float>::min();
std::numeric_limits<float>::infinity();

As noted in the comments, min()returns the lowest possible positive value. In other words the positive value closest to 0 that can be represented. The lowest possible value is the negative of the maximum possible value.

如评论中所述,min()返回尽可能低的正值。换句话说,可以表示最接近 0 的正值。可能的最低值是最大可能值的负值。

There is of course the std::max_elementand min_element functions (defined in <algorithm>) which may be a better choice for finding the largest or smallest value in an array.

当然std::max_element还有 min_element 函数(在 中定义<algorithm>),它们可能是查找数组中最大值或最小值的更好选择。

回答by MSN

You can either use -FLT_MAX(or -DBL_MAX) for the maximum magnitude negative number and FLT_MAX(or DBL_MAX) for positive. This gives you the range of possible float (or double) values.

您可以使用-FLT_MAX(或-DBL_MAX) 表示最大幅度负数,而FLT_MAX(或DBL_MAX) 表示正数。这为您提供了可能的浮点(或双精度)值的范围。

You probably don't want to use FLT_MIN; it corresponds to the smallest magnitude positive number that can be represented with a float, not the most negative value representable with a float.

您可能不想使用FLT_MIN; 它对应于可以用浮点数表示的最小量级正数,而不是可以用浮点数表示的最负值。

FLT_MINand FLT_MAXcorrespond to std::numeric_limits<float>::min()and std::numeric_limits<float>::max().

FLT_MINFLT_MAX对应于std::numeric_limits<float>::min()std::numeric_limits<float>::max()

回答by Jerry Coffin

There's no real need to initialize to smallest/largest possible to find the smallest/largest in the array:

没有真正需要初始化为最小/最大可能找到数组中的最小/最大:

double largest = smallest = array[0];
for (int i=1; i<array_size; i++) {
    if (array[i] < smallest)
        smallest = array[i];
    if (array[i] > largest0
        largest= array[i];
}

Or, if you're doing it more than once:

或者,如果您不止一次这样做:

#include <utility>

template <class iter>
std::pair<typename iter::value_type, typename iter::value_type> find_extrema(iter begin, iter end) {
    std::pair<typename iter::value_type, typename iter::value_type> ret;
    ret.first = ret.second = *begin;
    while (++begin != end) {
        if (*begin < ret.first)
           ret.first = *begin;
        if (*begin > ret.second)
           ret.second = *begin;
   }
   return ret;
}

The disadvantage of providing sample code -- I see others have already suggested the same idea.

提供示例代码的缺点——我看到其他人已经提出了同样的想法。

Note that while the standard has a min_element and max_element, using these would require scanning through the data twice, which could be a problem if the array is large at all. Recent standards have addressed this by adding a std::minmax_element, which does the same as the find_extremaabove (find both the minimum and maximum elements in a collection in a single pass).

请注意,虽然标准有 min_element 和 max_element,但使用它们需要扫描数据两次,如果数组很大,这可能是一个问题。最近的标准通过添加 a 解决了这个问题std::minmax_element,它的作用与find_extrema上述相同(在一次通过中查找集合中的最小和最大元素)。

Edit: Addressing the problem of finding the smallest non-zero value in an array of unsigned: observe that unsigned values "wrap around" when they reach an extreme. To find the smallest non-zero value, we can subtract one from each for the comparison. Any zero values will "wrap around" to the largest possible value for the type, but the relationshipbetween other values will be retained. After we're done, we obviously add one back to the value we found.

编辑:解决在无符号数组中找到最小非零值的问题:观察无符号值在达到极端时“环绕”。为了找到最小的非零值,我们可以从每个值中减去一个进行比较。任何零值都将“环绕”到该类型的最大可能值,但将保留其他值之间的关系。完成后,我们显然会在找到的值上加一。

unsigned int min_nonzero(std::vector<unsigned int> const &values) { 
    if (vector.size() == 0)
        return 0;
    unsigned int temp = values[0]-1;
    for (int i=1; i<values.size(); i++)
        if (values[i]-1 < temp)
            temp = values[i]-1;
    return temp+1;
}

Note this still uses the first element for the initial value, but we still don't need any "special case" code -- since that will wrap around to the largest possible value, any non-zero value will compare as being smaller. The result will be the smallest nonzero value, or 0 if and only if the vector contained no non-zero values.

请注意,这仍然使用第一个元素作为初始值,但我们仍然不需要任何“特殊情况”代码——因为这将环绕到可能的最大值,任何非零值都将比较为更小。结果将是最小的非零值,或者当且仅当向量不包含非零值时为 0。

回答by Bill

To manually find the minimum of an array you don't need to know the minimum value of float:

要手动查找数组的最小值,您不需要知道 float 的最小值:

float myFloats[];
...
float minimum = myFloats[0];
for (int i = 0; i < myFloatsSize; ++i)
{
  if (myFloats[i] < minimum)
  {
    minimum = myFloats[i];
  }
}

And similar code for the maximum value.

和最大值的类似代码。

回答by Thomas Padron-McCarthy

May I suggest that you initialize your "max and min so far" variables not to infinity, but to the first number in the array?

我可以建议您将“到目前为止的最大和最小”变量初始化为无穷大,而是将其初始化为数组中的第一个数字吗?