LISP-小数点后的数字

问题描述:

有人知道如何指定Lisp中浮点数小数点后的位数吗?

does anyone know how to specify the numer of digits after the decimal point for a float in Lisp?

请问是否在REPL上打印此命令:

Say if I print this command at the REPL:

CL-USER 3 > (format t "~,15f" (float (/ 1 7)))

我得到:

0.142857150000000 

但是数字四舍五入到小数点后的第8位,我需要查看小数点后的很多数字,以便查看数字是否是循环的并计算周期. (实际上,我开始尝试解决Euler项目的问题26).

But the number is rounded at the 8th digit after the decimal point, I need to see a lot of digits after the decimal point in order to see if the number is cyclic and to calculate the period. (Actually I'm starting to try and solve Project Euler's problem 26).

我需要得到这样的东西:

I need to get something like this:

CL-USER 3 > (format t "~,15f" (float (/ 1 7)))
0.142857142857142857142857142857142857.... 

谢谢

路卡

Common Lisp在其标准中没有具有任意精确度的浮点数.

Common Lisp does not have floats with arbitrary exactness in its standard.

Common Lisp在标准中定义了四种浮点类型:SHORT-FLOATSINGLE-FLOATDOUBLE-FLOATLONG-FLOAT.

Common Lisp defines four float types in the standard: SHORT-FLOAT, SINGLE-FLOAT, DOUBLE-FLOAT, LONG-FLOAT.

您可以使用函数COERCE(例如LispWorks中的示例)将比率强制转换为浮点数:

You can coerce a ratio to a float using the function COERCE (example in LispWorks):

CL-USER 1 > (coerce (/ 1 7) 'double-float)
0.14285714285714285D0

或在CLISP中作为LONG-FLOAT

or as a LONG-FLOAT in CLISP

[1]> (coerce (/ 1 7) 'long-float)
0.14285714285714285714L0

要使用更长的浮点数进行计算,您需要扩展Common Lisp. GNU CLISP 具有不可移植的扩展名,可以设置(二进制)位数:

To compute with longer float numbers you need extensions to Common Lisp. GNU CLISP has a non-portable extension and can set the number of (binary) digits:

(SETF (EXT:LONG-FLOAT-DIGITS) n)

示例:

[3]> (SETF (EXT:LONG-FLOAT-DIGITS) 1000)    
1000
[4]> (coerce (/ 1 7) 'long-float)
0.142857142857142857142857142857142857142857142857142857
142857142857142857142857142857142857142857142857142857
142857142857142857142857142857142857142857142857142857
142857142857142857142857142857142857142857142857142857
142857142857142857142857142857142857142857142857142857
142857142857142857142857142857142857143L0