@@ -426,9 +426,6 @@ pytime_double_to_time_t(time_t *sec, double value)
426426 assumption that time_t is a two's complement integer type with no trap
427427 representation, and that `PY_TIME_T_MIN` is within the representable
428428 range of a C double.
429-
430- Note: we want the `if` condition below to be true for NaNs; therefore,
431- resist any temptation to simplify by applying De Morgan's laws.
432429 */
433430 const double time_t_min = (double )PY_TIME_T_MIN ;
434431 if (!(time_t_min <= value && value < - time_t_min )) {
@@ -442,7 +439,7 @@ pytime_double_to_time_t(time_t *sec, double value)
442439
443440
444441// Convert C double to C PyTime_t.
445- // Set *sec and return 0 on success.
442+ // Set *tp and return 0 on success.
446443// Set OverflowError and return -1 on overflow.
447444//
448445// See also pytime_double_to_time_t().
@@ -917,23 +914,48 @@ pytime_from_pyfloat(PyTime_t *tp, PyObject *obj, _PyTime_round_t round,
917914{
918915 double value = PyFloat_AsDouble (obj );
919916 if (value == -1 && PyErr_Occurred ()) {
917+ * tp = 0 ;
920918 return -1 ;
921919 }
922920
923921 if (isnan (value )) {
924922 PyErr_SetString (PyExc_ValueError , "Invalid value NaN (not a number)" );
923+ * tp = 0 ;
925924 return -1 ;
926925 }
927926
927+ double intpart ;
928928 /* volatile avoids optimization changing how numbers are rounded */
929- volatile double d ;
929+ volatile double floatpart ;
930930
931- /* convert to a number of nanoseconds */
932- d = value ;
933- d *= (double )unit_to_ns ;
934- d = pytime_round (d , round );
931+ // Multiply by unit_to_ns using integers (PyTime_t), instead of double
932+ // to avoid loss of precision.
933+ floatpart = modf (value , & intpart );
934+ PyTime_t t ;
935+ if (pytime_from_double_cast (& t , intpart ) < 0 ) {
936+ * tp = 0 ;
937+ return -1 ; // overflow
938+ }
939+ if (pytime_mul (& t , unit_to_ns ) < 0 ) {
940+ pytime_overflow ();
941+ return -1 ;
942+ }
943+
944+ floatpart *= unit_to_ns ;
945+ floatpart = pytime_round (floatpart , round );
946+ // It's safe to cast floatpart to PyTime_t, since its value is in
947+ // the range [-unit_to_ns; unit_to_ns], where unit_to_ns maximum
948+ // is SEC_TO_NS (for _PyTime_FromSecondsObject()).
949+ assert (- unit_to_ns <= floatpart && floatpart <= unit_to_ns );
950+
951+ PyTime_t ns = (PyTime_t )floatpart ;
952+ if (pytime_add (& t , ns ) < 0 ) {
953+ pytime_overflow ();
954+ return -1 ;
955+ }
935956
936- return pytime_from_double_cast (tp , d );
957+ * tp = t ;
958+ return 0 ;
937959}
938960
939961
0 commit comments