[plt-scheme] Numerical precision
#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