我一直在阅读CS61A (Spring 2011)Berkeley OpencoursewareMIT 6.001OCW的课程。一个使用STk(称为stk-simply),另一个使用mit-scheme作为讲座的编程语言。

我只是使用Heron's method编写了一个简单的平方根过程。该文件另存为sqrt.scm

;; setting an accuracy or tolerance to deviation between the actual and the expected values
(define tolerance 0.001)

;; gives average of two numbers
(define (average x y)
  (/ (+ x y) 2))

;; gives the absolute values of any number
(define (abs x)
  (if (< x 0) (- x) x))

;; gives the square of a number
(define (square x) (* x x))

;; tests whether the guess is good enough by checking if the difference between square of the guess
;; and the number is tolerable
(define (good-enuf? guess x)
  (< (abs (- (square guess) x)) tolerance))

;; improves the guess by averaging guess the number divided by the guess
(define (improve guess x)
  (average (/ x guess) guess))

;;  when a tried guess does not pass the good-enuf test then the tries the improved guess
(define (try guess x)
  (if (good-enuf? guess x)
      guess
      (try (improve guess x) x)))

;; gives back square root of number by starting guess with 1 and then improving the guess until good-enuf
(define (sqr-root x)
  (try 1 x))


这在STk中工作正常。

sam@Panzer:~/code/src/scheme$ sudo stk-simply
[sudo] password for sam:
Welcome to the STk interpreter version 4.0.1-ucb1.3.6 [Linux-2.6.16-1.2108_FC4-i686]
Copyright (c) 1993-1999 Erick Gallesio - I3S - CNRS / ESSI <[email protected]>
Modifications by UCB EECS Instructional Support Group
Questions, comments, or bug reports to <[email protected]>.
STk> (load "sqrt.scm")
okay
STk> (sqr-root 25)
5.00002317825395
STk>


但是没有计划。

sam@Panzer:~/code/src/scheme$ sudo scheme
[sudo] password for sam:
MIT/GNU Scheme running under GNU/Linux
Type `^C' (control-C) followed by `H' to obtain information about interrupts.

Copyright (C) 2011 Massachusetts Institute of Technology
This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Image saved on Thursday October 27, 2011 at 7:44:21 PM
  Release 9.1 || Microcode 15.3 || Runtime 15.7 || SF 4.41 || LIAR/i386 4.118 || Edwin 3.116

1 ]=> (load "sqrt.scm")

;Loading "sqrt.scm"... done
;Value: sqr-root

1 ]=> (sqr-root 25)

;Value: 1853024483819137/370603178776909

1 ]=>


我检查了手册,但找不到原因。谁能告诉我这是为什么吗?还是我忽略的代码中有错误?我是计划和STk的初学者。

最佳答案

试试看,现在代码在两个解释器中应该返回相同的结果(忽略微小的舍入差异):

(define (sqr-root x)
  (exact->inexact (try 1 x)))


答案一直都是一样的,只是MIT方案默认情况下会产生准确的结果,而STk返回的是不精确的值。使用上面的代码,我们在执行计算后将结果转换为不精确的数字。或者,我们可以从头开始执行转换(可能会在过程中失去一些精度):

(define (sqr-root x)
  (try 1 (exact->inexact x)))


quote解释了观察到的行为:


方案编号是准确的还是不精确的。如果数字写为精确常数或仅使用精确运算从精确数字派生,则该数字是精确的。如果将数字写为不精确的常数,使用不精确的成分得出的数字或使用不精确的运算得出的数字,则该数字是不精确的。因此,不精确性是数字的传染性。

关于scheme - 代码仅在stk中起作用,但在mit-scheme中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16743537/

10-09 02:59