Mentions légales du service

Skip to content
Snippets Groups Projects

Rephrase NaN Inf section for integral and floating point types

All threads resolved!
1 file
+ 34
0
Compare changes
  • Side-by-side
  • Inline
(see the [CppReference dedicated page](https://en.cppreference.com/w/cpp/types/numeric_limits) for more details about `std::numeric_limits`).
(see the [CppReference dedicated page](https://en.cppreference.com/w/cpp/types/numeric_limits) for more details about `std::numeric_limits`).
 
##### Integral types
 
If an initial value is not in the range, the compiler will yell:
If an initial value is not in the range, the compiler will yell:
Other languages such as Python (but not its numeric modules such as _numpy_ which are using C or C++ under the hood) gets a underlying integer model that is resilient to this kind of issue but there is a performance cost behind it; types such as those used in C++ are tailored to favor optimization on your hardware.
Other languages such as Python (but not its numeric modules such as _numpy_ which are using C or C++ under the hood) gets a underlying integer model that is resilient to this kind of issue but there is a performance cost behind it; types such as those used in C++ are tailored to favor optimization on your hardware.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
 
##### Floating-point types
 
 
C++ provides special values to represent infinite or not-a-number values for floating-point types (the facilities below appeared after C++ 11; there were others prior to that inherited directly from C).
 
%% Cell type:code id: tags:
 
``` C++17
 
#include <cmath>
 
#include <iostream>
 
 
float max_float {std::numeric_limits<float>::max()};
 
max_float += 1.e+32; // Add something significant enough to max value
 
std::cout << "Is " << max_float << " infinite ? " << std::isinf(max_float) << std::endl;
 
max_float -= 1.e+32;
 
std::cout << "Is " << max_float << " infinite ? " << std::isinf(max_float) << std::endl;
 
 
double nan = 0. / 0.;
 
 
std::cout << "Is " << nan << " infinite ? " << std::isinf(nan) << std::endl;
 
std::cout << "Is " << nan << " not-a-number ? " << std::isnan(nan) << std::endl;
 
nan = nan + 1.e5;
 
std::cout << "Is " << nan << " not-a-number ? " << std::isnan(nan) << std::endl;
 
 
std::cout << "The unnatural property of nan is that the expression 'nan == nan' is " << std::boolalpha << (nan == nan) << "!" << std::endl;
 
%% Cell type:markdown id: tags:
 
There are subtleties about NaN (see [Cppreference](https://en.cppreference.com/w/cpp/numeric/math/nan)) but in most cases you don't need to bother much with either `inf` or `nan`, except if you have reasons to think your computation may produce either of them. In that case, you may want to check your value is correct with `std::isfinite` ([Cppreference](https://en.cppreference.com/w/cpp/numeric/math/isfinite)).
 
%% Cell type:markdown id: tags:
Loading