Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 535
Faken Avatar asked Apr 21 '10 16:04

Faken


People also ask

Does MIN () work with floats?

Method : Using min()/max() + float()This problem can be solved using the min or max function in which we first convert the strings into float and then pass this logic in functions in respective min/max function.

What is the max value of float in C++?

short: min: -32768 max: 32767 int: min: -2147483648 max: 2147483647 long: min: -2147483648 max: 2147483647 float: min: 1.17549e-038 max: 3.40282e+038 double: min: 2.22507e-308 max: 1.79769e+308 long double: min: 2.22507e-308 max: 1.79769e+308 unsigned short: min: 0 max: 65535 unsigned int: min: 0 max: 4294967295 ...

What is maximum and minimum range of float data type?

Since the high-order bit of the mantissa is always 1, it is not stored in the number. This representation gives a range of approximately 3.4E-38 to 3.4E+38 for type float.


1 Answers

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(); 

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.

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

like image 146
Yacoby Avatar answered Nov 01 '22 19:11

Yacoby