Computing Weighted Averages

It's easy to compute a weighted average incorrectly if you're not careful. A weighted average should have the property that if an assignment has a weight of, say 10% of the final grade, it should have that weight whether the assignment is graded on a scale of 100 or a scale of 20.

The following bit of code does the weighted-average algorithm correctly:

;; weighted-average : List-of-Number List-of-Number List-of-Number -> Number
(define (weighted-average scores maxes weights)
  (let ((weighted-sum
          (sum
            (map
              (lambda (score max weight) (* (/ score max) weight))
              scores maxes weights)))
        (total-weight (sum weights)))
    (/ weighted-sum total-weight)))

;; sum : List-of-Number -> Number
(define sum
  (lambda (l)
    (if (null? l) 0 (+ (car l) (sum (cdr l))))))

Mitchell Wand
College of Computer and Information Science, Northeastern University
360 Huntington Avenue #202 WVH,
Boston, MA 02115
Internet: wand@ccs.neu.edu
Phone: (617) 373-2072 / Fax: (617) 373-5121