如何将浮点数初始化为它的 max/min 值?

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

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

203334 次浏览

You can use std::numeric_limits which 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).

#include <limits>


//...


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

正如注释中指出的那样,min()返回尽可能低的正值。换句话说,可以表示的最接近于0的正值。最小可能值是最大可能值的负数。

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

要手动查找数组的最小值,不需要知道 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.

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

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];
}

或者,如果你做了不止一次:

#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.

请注意,虽然标准有一个 min _ element 和 max _ element,但是使用这两个元素需要扫描数据两次,如果数组很大,这可能是一个问题。最近的标准已经通过添加 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 关系 between 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;
}

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

您可以使用 -FLT_MAX(或 -DBL_MAX)的最大幅度负数和 FLT_MAX(或 DBL_MAX)的正面。这给出了可能的 float (或 double)值的范围。

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

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