[plt-scheme] Numerical precision

From: Chongkai Zhu (czhu at cs.utah.edu)
Date: Wed Mar 11 15:16:47 EDT 2009

#lang scheme

(provide numerical-precision
         (rename-out [round:N round]
                     [*:N *]
                     [/:N /]
                     [+:N +]
                     [-:N -]))

(define numerical-precision (make-parameter 2))

(define N
  (expt 10 (numerical-precision)))

(define 1/N
  (/ 1 N))

(define (round:N x)
  (* 1/N (round (* x N))))

(define (*:N . nums)
  (round:N (apply * nums)))

(define (/:N . nums)
  (round:N (apply / nums)))

(define (+:N . nums)
  (round:N (apply + nums)))

(define (-:N . nums)
  (round:N (apply - nums)))


-
Chongkai

Jaime Vargas wrote:
> Hi,
>
> I am doing some personal financial simulations and need math procedures
> that keep N digits of numerical precision. For this I am using 
> Scheme's exact
> numbers and wrote the attached naive implementation.
>
> Given that I am no math guru is there something that I should worry about
> this implementation? Also, I would like to optimize the round:N 
> procedure to
> avoid calculating N and 1/N all the time. I thought that LET will 
> help, but it did
> not.
>
> Thanks,
>
> Jaime E Vargas
>
>
> #lang scheme
>
> (provide numerical-precision
>          (rename-out [round:N round]
>                      [*:N *]
>                      [/:N /]
>                      [+:N +]
>                      [-:N -]))
>
> (define numerical-precision (make-parameter 2))
>
> (define (N)
>   (expt 10 (numerical-precision)))
>
> (define (1/N)
>   (/ 1 (N)))
>
> (define (round:N x)
>   (* (1/N) (round (* x (N)))))
>
> (define (*:N . nums)
>   (round:N (apply * nums)))
>
> (define (/:N . nums)
>   (round:N (apply / nums)))
>
> (define (+:N . nums)
>   (round:N (apply + nums)))
>
> (define (-:N . nums)
>   (round:N (apply - nums)))
>
> _________________________________________________
>  For list-related administrative tasks:
>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme



Posted on the users mailing list.