Round To 5
August 13, 2019
We begin by creating a random list of speed readings, biasing it so the round-to-5 speed will be 50:
(define speeds (do ((n 100 (- n 1)) (xs (list) (cons (+ (random 19.0) 40) xs))) ((zero? n) xs)))
The actual average of the speeds we generated is 49.6 mph:
(define (average xs) (/ (apply + xs) (length xs)))
> (average speeds) 49.59251941983793
Now we need a function to round a number to the nearest 5:
(define (round5 x) (inexact->exact (* (floor (/ (+ x 2.5) 5)) 5)))
> (round5 (average speeds)) 50
A simple solution to a simple problem. You can run the program at https://ideone.com/wqc57b.
Here is a slightly more general solution in standard R7RS Scheme (and
a couple of SRFI helpers only for testing). It allows rounding to
non-integer values too, e.g., the nearest multiple of 25, as the demo
illustrates.
Output:
Klong version: 10 iterations
Here’s a solution in Python.
Output:
Rust version