[Python-checkins] python/dist/src/Modules datetimemodule.c,1.24,1.25

tim_one@users.sourceforge.net tim_one@users.sourceforge.net
Thu, 02 Jan 2003 08:32:59 -0800


Update of /cvsroot/python/python/dist/src/Modules
In directory sc8-pr-cvs1:/tmp/cvs-serv32028/python/Modules

Modified Files:
	datetimemodule.c 
Log Message:
SF bug 661086: datetime.today() truncates microseconds.
On Windows, it was very common to get microsecond values (out of
.today() and .now()) of the form 480999, i.e. with three trailing
nines.  The platform precision is .001 seconds, and fp rounding
errors account for the rest.  Under the covers, that 480999 started
life as the fractional part of a timestamp, like .4809999978.
Rounding that times 1e6 cures the irritation.

Confession:  the platform precision isn't really .001 seconds.  It's
usually worse.  What actually happens is that MS rounds a cruder value
to a multiple of .001, and that suffers its own rounding errors.

A tiny bit of refactoring added a new internal utility to round
doubles.


Index: datetimemodule.c
===================================================================
RCS file: /cvsroot/python/python/dist/src/Modules/datetimemodule.c,v
retrieving revision 1.24
retrieving revision 1.25
diff -C2 -d -r1.24 -r1.25
*** datetimemodule.c	2 Jan 2003 03:14:59 -0000	1.24
--- datetimemodule.c	2 Jan 2003 16:32:54 -0000	1.25
***************
*** 121,124 ****
--- 121,137 ----
  }
  
+ /* Round a double to the nearest long.  |x| must be small enough to fit
+  * in a C long; this is not checked.
+  */
+ static long
+ round_to_long(double x)
+ {
+ 	if (x >= 0.0)
+ 		x = floor(x + 0.5);
+ 	else
+ 		x = ceil(x - 0.5);
+ 	return (long)x;
+ }
+ 
  /* ---------------------------------------------------------------------------
   * General calendrical helper functions
***************
*** 1906,1915 ****
  	if (leftover_us) {
  		/* Round to nearest whole # of us, and add into x. */
! 		PyObject *temp;
! 		if (leftover_us >= 0.0)
! 			leftover_us = floor(leftover_us + 0.5);
! 		else
! 			leftover_us = ceil(leftover_us - 0.5);
! 		temp = PyLong_FromDouble(leftover_us);
  		if (temp == NULL) {
  			Py_DECREF(x);
--- 1919,1923 ----
  	if (leftover_us) {
  		/* Round to nearest whole # of us, and add into x. */
! 		PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
  		if (temp == NULL) {
  			Py_DECREF(x);
***************
*** 2859,2863 ****
  {
  	time_t timet = (time_t)timestamp;
! 	int us = (int)((timestamp - (double)timet) * 1e6);
  
  	return datetime_from_timet_and_us(cls, f, timet, us);
--- 2867,2872 ----
  {
  	time_t timet = (time_t)timestamp;
! 	double fraction = timestamp - (double)timet;
! 	int us = (int)round_to_long(fraction * 1e6);
  
  	return datetime_from_timet_and_us(cls, f, timet, us);