Why is modf output being forced to be double?
The function modf
splits the argument double
into integral and fractional parts; for example, when given, 3.75
it returns 3.0
and stores 0.75
in the object pointed to by its second argument.
The question is, what should happen if you call it too large for any integer type?
If it returns a result, int
or even a result long long
or intmax_t
, it will have to deal with the overflow in some way, which will most likely require adding an extra parameter to distinguish valid results from overflow.
double
Overflow is not possible by returning a result ; for very large arguments, it can simply return the value of the argument and set the fractional part to 0.0
. This greatly simplifies the function. (If you want to convert the result to an integer, you can, but you must check the result based on the constraints of the integer you are using.)
In modern systems, double
it is typically 64 bits and can accurately represent integers up to about 253 . If you call modf
with a value greater than 2 53 then the value itself double
cannot contain an exact integer value; with a return, modf
even a 64-bit integer would not provide any additional precision.
A long double
, depending on the implementation, can contain a wider range of precise integer values ββthan even the widest integer type; on such a system, returning modfl
an integer will lose precision as to what it returns long double
.
Thus, having modf
(and modff
and modfl
) returns an integer, not a floating point value, will lose range without any corresponding gain in precision.
source to share