Float Precision and Removing Rounding Errors in Scheme

floating-point, lisp, precision, rounding, scheme

Solution

Try

(define (round-off z n)
  (let ((power (expt 10 n)))
    (/ (round (* power z)) power)))

> (round-off 3.665 2)
3.66
> (round-off 3.6677 2)
3.67

Note 3.665 rounds to 3.66, not 3.67. (Evens round down; odds round up)

As for your second question. Use exact numbers:

> (* 1 (- #e0.5 #e0.4 #e0.1))
0

> #e0.5
1/2

Problem

I have a procedure that returns a float to three decimal places. ``` >(gpa ’(A A+ B+ B)) 3.665 ``` Is there any way to round this to 3.67 in Scheme? I'm using SCM version 5e7 with Slib 3b3, the additional Simply Scheme libraries (simply.scm, functions.scm, ttt.scm, match.scm, database.scm) and the answer library I use loaded. As an aside, I input this into my computer this morning ``` > (* 1 (- 0.5 0.4 0.1)) -27.755575615628913e-18 ``` no no no no! How do you deal with such inaccuracy?

Original source