off-by-one error in SRFI 19's date-week-number procedure? voegelas@xxxxxx (25 Apr 2004 17:24 UTC)
Re: off-by-one error in SRFI 19's date-week-number procedure? Andreas Vögele (25 Apr 2004 17:39 UTC)

off-by-one error in SRFI 19's date-week-number procedure? voegelas@xxxxxx 25 Apr 2004 17:24 UTC

While browsing Guile's regression tests I came across the following
test which checks the procedure date-week-number:

  (with-test-prefix "date-week-number"
    (pass-if (= 0 (date-week-number (make-date 0 0 0 0 1 1 1984 0) 0)))
    (pass-if (= 0 (date-week-number (make-date 0 0 0 0 7 1 1984 0) 0)))
    (pass-if (= 1 (date-week-number (make-date 0 0 0 0 8 1 1984 0) 0)))))

I executed the second date-week-number expression with Guile, Scsh,
and MzScheme.  All three Scheme implementations return 1 instead of 0:

  $ guile --version
  Guile 1.6.4
  $ guile
  guile> (use-modules (srfi srfi-19))
  guile> (date-week-number (make-date 0 0 0 0 7 1 1984 0) 0)
  1

  $ scsh -o srfi-19
  Welcome to scsh 0.6.5 (0.6.6)
  Type ,? for help.
  > (date-week-number (make-date 0 0 0 0 7 1 1984 0) 0)
  1

  $ mzscheme
  Welcome to MzScheme version 206p1, Copyright (c) 2004 PLT Scheme, Inc.
  > (require (lib "19.ss" "srfi"))
  > (tm:date-week-number (tm:make-date 0 0 0 0 7 1 1984 0) 0)
  1

Guile, Scsh and MzScheme use the same implementation of
date-week-number:

  (define (date-week-number date day-of-week-starting-week)
    (quotient (- (date-year-day date)
	         (tm:days-before-first-week  date day-of-week-starting-week))
	      7))

The description of date-week-number in SRFI 19 says:

  date-week-number date day-of-week-starting-week -> integer

  The ordinal week of the year which holds this date, ignoring a first
  partial week. 'Day-of-week-starting-week' is the integer
  corresponding to the day of the week which is to be considered the
  first day of the week (Sunday=0, Monday=1, etc.)."

1984 starts with a Sunday:

     January 1984
   S  M Tu  W Th  F  S
   1  2  3  4  5  6  7
   8  9 10 11 12 13 14
  15 16 17 18 19 20 21
  22 23 24 25 26 27 28
  29 30 31

If the ordinal week is zero based and Sunday is the first day of the
week, I'd expect January, 1st 1984 to be in week 0 and January, 8th to
be in week 1:

  (date-week-number (make-date 0 0 0 0 1 1 1984 0) 0) => 0
  (date-week-number (make-date 0 0 0 0 8 1 1984 0) 0) => 1

But why is the January, 6th (a Friday) in week 0 and January, 7th in
week 1?

  (date-week-number (make-date 0 0 0 0 6 1 1984 0) 0) => 0
  (date-week-number (make-date 0 0 0 0 7 1 1984 0) 0) => 1

It seems that there is an off-by-one error.  Here's a modified version
of date-week-number:

  (define (date-week-number date day-of-week-starting-week)
    (quotient (- (date-year-day date)
                 (tm:days-before-first-week  date day-of-week-starting-week)
                 1)
              7))

I've checked it briefly and it seems to return the right values.