float를 최대 / 최소 값으로 어떻게 초기화합니까?
float 또는 double의 절대 최대 값 또는 최소값을 어떻게 하드 코딩합니까? 단순히 반복하고 가장 큰 것을 잡아서 배열의 최대 / 최소를 검색하고 싶습니다.
float에 대한 양수 및 음수 무한대도 있습니다. 대신 사용해야합니까? 그렇다면 코드에서 어떻게 표시합니까?
에 std::numeric_limits정의 된 <limits>것을 사용 하여 유형의 최소 또는 최대 값을 찾을 수 있습니다 (유형에 대한 전문화가 존재하는 한). 무한대를 검색하는 데 사용할 수도 있습니다 (그리고 -음의 무한대를 앞에 두는 경우 ).
#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>)가 있습니다.
최대 크기 음수에는 (또는 )을 사용하고 양수 에는 -FLT_MAX(또는 -DBL_MAX)을 사용할 수 있습니다 . 이것은 가능한 float (또는 double) 값의 범위를 제공합니다.FLT_MAXDBL_MAX
사용하고 싶지 않을 것입니다 FLT_MIN. 이것은 float로 나타낼 수있는 가장 작은 양의 값이 아니라 float로 나타낼 수있는 가장 작은 양수에 해당합니다.
FLT_MIN및 FLT_MAX대응 std::numeric_limits<float>::min()과 std::numeric_limits<float>::max().
배열에서 가장 작은 / 가장 큰 것을 찾기 위해 가능한 가장 작은 / 최대로 초기화 할 필요가 없습니다.
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;
}
샘플 코드 제공의 단점-다른 사람들이 이미 동일한 아이디어를 제안한 것으로 보입니다.
표준에는 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 relationship 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;
}
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.
To manually find the minimum of an array you don't need to know the minimum value of 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?
참고URL : https://stackoverflow.com/questions/2684603/how-do-i-initialize-a-float-to-its-max-min-value
'IT박스' 카테고리의 다른 글
| SQL 명령을 통해 MySQL 호스트 표시 (0) | 2020.09.05 |
|---|---|
| yyyyMMddHHmmss 형식을 사용하여 현재 시간을 포맷하는 방법은 무엇입니까? (0) | 2020.09.05 |
| PHP로 IP 주소 국가 가져 오기 (0) | 2020.09.05 |
| 터미널에서 Ruby 코드를 실행하는 방법은 무엇입니까? (0) | 2020.09.05 |
| Dockerfile의 이름을 지정하는 방법 (0) | 2020.09.05 |