[plt-scheme] Numerical precision
From: Jaime Vargas (jev at mac.com)
Date: Wed Mar 11 15:34:45 EDT 2009 |
|
Chongkai,
Your version doesn't work. N and 1/N become permanently bound and
independent from parameter changes.
#lang scheme
(require (only-in "accountants-math.ss" numerical-precision round))
(for ([i (in-range 5)])
(parameterize ([numerical-precision i])
(print (round (* 6125/10000 (* 100 6125/100000))))
(newline)))
Your version prints:
3 3/4
3 3/4
3 3/4
3 3/4
3 3/4
Mine:
4
3 4/5
3 3/4
3 94/125
3 1879/2500
Thanks,
Jaime
On Mar 11, 2009, at 3:16 PM, Chongkai Zhu wrote:
> #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
>