0 Replies - 1366 Views - Last Post: 14 June 2011 - 09:18 PM

#1 I X Code X 1   User is offline

  • D.I.C Head
  • member icon

Reputation: 47
  • View blog
  • Posts: 66
  • Joined: 28-July 10

[Lisp] Common Lisp - Advanced Rounding

Posted 14 June 2011 - 09:18 PM

Description: Should work in any lisp implementation; I used Allegro Common Lisp Express Edition.Two functions: One rounds a given number UP to the nearest multiple of the rounding factor it is given, and Two rounds the given number to the nearest multiple of the rounding factor. Also, illustrates the functionality of let* as opposed to let.
;;;; One

(defun round-up (n r)
  (let* ((x (/ r 2.0))
         (m (+ n x)))
    (* r (round (/ m r)))))

; round-up is given a number, n, and a rounding factor, r.

; We use a let* because we need to be able to use the variables in the let 
; expression. A simple let does not allow us to do that.

; x is the rounding factor / 2.0 and m is the number + the value x evaluated

; Then we simply divide m by r, round that value and multiply by the 
; rounding factor. Works every time!

CG-USER(48): (round-up 17 7)

21 
CG-USER(49): (round-up 1 5)

5 


;;;; Two


(defun round-it (n r)
  (let* ((x (/ n r))
         (m (round x)))
    (* m r)))

;round-it is given a number, n, and a rounding factor, r.

; Again, we have to use let* in our variable deceleration.

; The rest is simple math -> x is n / r and then we simply round x which
; is set to m and then multiply m by r, the rounding factor!

CG-USER(53): (round-it 12 5)
10
CG-USER(54): (round-it 13 5)
15


;; These two functions can come in handy when you need to specify what way
;; a number needs to be rounded.


Is This A Good Question/Topic? 0
  • +

Page 1 of 1