【发布时间】:2018-11-14 07:43:21
【问题描述】:
我正在做 SICP 的练习。
在 Ex1.22 中,我有一个关于 Scheme 中科学记数法性能的问题。
这个练习是找出大于指定值的素数的指定计数。
; code to check whether a number is prime
(define (smallest-divisor n)
(find-divisor n 2))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (1+ test-divisor)))))
(define (divides? a b)
(= (remainder b a) 0))
(define (prime? n)
(= n (smallest-divisor n)))
; code to find prime numbers
; (search-for-primes 10 3) means find 3 prime numbers larger than 10
; the prime numbers and the time taken will be printed
(define (search-for-primes start count)
(define (iter n c)
(cond ((= c 0) (newline) (display "Done"))
(else (iter (+ n 2) (- c (timed-prime-test n))))))
(iter (if (even? start) (1+ start) start)
count))
(define (timed-prime-test n)
(newline)
(display n)
(start-prime-test n (runtime)))
(define (start-prime-test n start-time)
(cond ((prime? n)
(report-prime (- (runtime) start-time))
1)
(else 0)))
(define (report-prime elapsed-time)
(display " *** ")
(display elapsed-time))
我的问题是以下两个调用的性能差异:
1 ]=> (search-for-primes 1000000000000 3)
1000000000039 *** 2.319999999999993
1000000000061 *** 2.3799999999999955
1000000000063 *** 2.3599999999999994
1 ]=> (search-for-primes 1e12 3)
1000000000039. *** 4.990000000000009
1000000000061. *** 4.960000000000008
1000000000063. *** 4.959999999999994
显然科学记数法需要更多时间。为什么会这样?
我的代码在最新版本的 MIT-Scheme 上运行:
MIT/GNU Scheme running under GNU/Linux
Type `^C' (control-C) followed by `H' to obtain information about interrupts.
Copyright (C) 2018 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 Wednesday October 31, 2018 at 7:14:37 PM
Release 10.1.2 || Microcode 15.3 || Runtime 15.7 || SF 4.41 || LIAR/i386 4.118
【问题讨论】:
-
科学记数法可能意味着该数字是浮点数。
-
您应该尝试
#e1e12看看是否可以解决问题。 -
你们俩都是对的。非常感谢您的回答。
-
@PetSerAI 你能把你的话复制到正式答案吗?然后我可以标记它并关闭这个问题。
标签: scheme scientific-notation sicp