Floating Point Types
Explore floating point types in D programming to understand how they handle fractional values and special cases like .nan and infinity. Learn their properties, precision details, and how floating point expressions behave differently from integers, helping you write accurate numerical code.
We'll cover the following...
Earlier in this chapter, we have seen that, despite their ease of use, arithmetic operations on integers are prone to programming errors due to overflow and truncation. We have also seen that integer type variables cannot have values with fractional parts, as in 1.25.
Floating point types
Floating point types are designed to support fractional parts. The “point” in their name comes from the radix point, which separates the integer part from the fractional part, and “floating” refers to the detail in how these types are implemented. The decimal point floats left and right as the number of digits is not fixed before and after the decimal point.
Here are some interesting aspects of floating point types:
-
Adding 0.001 a thousand times is not the same as adding 1.
-
Using the logical operators
==and!=with floating point types produces incorrect results in most cases. -
The initial value of floating point types is
.nan, not 0..nanmay not be used in expressions in any meaningful way. When used in comparison operations,.nanis neither less than nor greater than any value. -
There are two overflow values: positive .infinity and negative .infinity.
Although floating point types are more useful than integers in some cases, they have ...