Scheme中如何实现极高的浮点精度?

问题描述 投票:0回答:1

众所周知,Scheme 无需任何进一步的努力就可以产生极大的整数。

但是我该如何实现极高的浮点精度呢?谢谢。

(“极高”是指规定的精度,例如 1000 或点后 10000 位)

scheme precision
1个回答
2
投票

作为一种快速解决方案,您可以使用整数比率,并不时将中间结果舍入到所需的精度。

象征性地,

round_prec( Ratio(a,b), prec)  =  Ratio( round(a*10^prec / b), 10^prec)

其中

Ratio(a,b)
是符号数据,例如标记列表
(list 'RATIO numerator denominator)

在方案中,

(define (round-prec num denom prec)
   (list 'RATIO
         (round (/ (* num (expt 10 prec)) denom))
         (expt 10 prec)))

这是有效的,因为

/
可以正确地处理整数,并且我们要小心地先乘以
10^prec
,然后在除法之前,然后四舍五入。

用作例如

> (round-prec 10 3 1) '(RATIO 33 10) > (round-prec 10 3 10) '(RATIO 33333333333 10000000000)
使用

(exact->inexact (/ num denom))

将其转换为常规浮点数后可以轻松打印,例如

> (exact->inexact (/ 33333333333 10000000000)) 3.3333333333
您可以轻松定义常用的数字运算,例如

mult( Ratio(a,b), Ratio(c,d)) = Ratio( (a*c), (b*d) ) sum( Ratio(a,b), Ratio(c,d)) = Ratio( (a*d + c*b), (b*d) )
等等

© www.soinside.com 2019 - 2024. All rights reserved.