diff --git a/1-ProceduralProgramming/3-Types.ipynb b/1-ProceduralProgramming/3-Types.ipynb index fb6352b7de67e2c1daccc57e0e9a37edec1f2198..53b9ce315748c904d4167ec01154f9a058cb4060 100644 --- a/1-ProceduralProgramming/3-Types.ipynb +++ b/1-ProceduralProgramming/3-Types.ipynb @@ -319,6 +319,8 @@ "source": [ "(see the [CppReference dedicated page](https://en.cppreference.com/w/cpp/types/numeric_limits) for more details about `std::numeric_limits`).\n", "\n", + "##### Integral types\n", + "\n", "If an initial value is not in the range, the compiler will yell:" ] }, @@ -373,6 +375,47 @@ "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", + "metadata": {}, + "source": [ + "##### Floating-point types\n", + "\n", + "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", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#include <cmath>\n", + "#include <iostream>\n", + "\n", + "float max_float {std::numeric_limits<float>::max()};\n", + "max_float += 1.e+32; // Add something significant enough to max value\n", + "std::cout << \"Is \" << max_float << \" infinite ? \" << std::isinf(max_float) << std::endl;\n", + "max_float -= 1.e+32;\n", + "std::cout << \"Is \" << max_float << \" infinite ? \" << std::isinf(max_float) << std::endl;\n", + "\n", + "double nan = 0. / 0.;\n", + "\n", + "std::cout << \"Is \" << nan << \" infinite ? \" << std::isinf(nan) << std::endl;\n", + "std::cout << \"Is \" << nan << \" not-a-number ? \" << std::isnan(nan) << std::endl;\n", + "nan = nan + 1.e5;\n", + "std::cout << \"Is \" << nan << \" not-a-number ? \" << std::isnan(nan) << std::endl;\n", + "\n", + "std::cout << \"The unnatural property of nan is that the expression 'nan == nan' is \" << std::boolalpha << (nan == nan) << \"!\" << std::endl;\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "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", "metadata": {},