[ create a new paste ] login | about

Project: programmingpraxis
Link: http://programmingpraxis.codepad.org/JZQwpzdb    [ raw code | output | fork ]

programmingpraxis - Scheme, pasted on Dec 18:
; interval arithmetic

(define (plus x y)
  (cons (+ (car x) (car y)) (+ (cdr x) (cdr y))))

(define (minus x y)
  (cons (- (car x) (cdr y)) (- (cdr x) (car y))))

(define (times x y)
  (cons (min (* (car x) (car y)) (* (car x) (cdr y))
             (* (cdr x) (car y)) (* (cdr x) (cdr y)))
        (max (* (car x) (car y)) (* (car x) (cdr y))
             (* (cdr x) (car y)) (* (cdr x) (cdr y)))))

(define (divide x y)
  (if (< (car y) 0 (cdr y))
      (error 'divide "divide by zero")
      (cons (min (/ (car x) (car y)) (/ (car x) (cdr y))
                 (/ (cdr x) (car y)) (/ (cdr x) (cdr y)))
            (max (/ (car x) (car y)) (/ (car x) (cdr y))
                 (/ (cdr x) (car y)) (/ (cdr x) (cdr y))))))

(define (ends->center x)
  (cons (/ (+ (car x) (cdr x)) 2)
        (/ (- (cdr x) (car x)) 2)))

(define (center->ends x)
  (cons (- (car x) (cdr x)) (+ (car x) (cdr x))))

(define x (cons 1 2))
(define y (cons 3 4))
(display (plus x y)) (newline)
(display (minus x y)) (newline)
(display (times x y)) (newline)
(display (divide x y)) (newline)
(display (ends->center x)) (newline)
(display (center->ends (cons 3/2 1/2))) (newline)
(display (divide x x)) (newline)


Output:
1
2
3
4
5
6
7
(4 . 6)
(-3 . -1)
(3 . 8)
(1/4 . 2/3)
(3/2 . 1/2)
(1 . 2)
(1/2 . 2)


Create a new paste based on this one


Comments: