I am running Emacs 24.5.1 on Windows 10 and working through the SICP. The MIT editor Edwin doesn't function well, especially on Windows. Racket appears to be a good alternative. I have installed both Racket and racket-mode and everything seems to run okay. However, racket-mode insists on pretty-printing my results. How do I get it to print in decimal form?
For example,
(require sicp)
(define (square x) (* x x))
(define (average x y)
(/ (+ x y) 2))
(define (improve guess x)
(average guess (/ x guess)))
(define (good-enough? guess x)
(< (abs (- (square guess) x)) 0.001))
(define (sqrt-iter guess x)
(if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
This produces results such as
> (sqrt-iter 1 2)
577/408
Lots of documentation comes up when I Google the terms "Racket" and "pretty-print," but I'm having no luck making sense of it. The Racket documentation seems to control pretty-printing via some variable beginning with 'pretty-print'. Yet nothing starting with racket- or pretty within M-x comes up. Maybe the fraction form isn't what Racket considers pretty-printing?
Start the the iteration with floating point numbers 1.0 and 2.0 rather than exact numbers 1 and 2.
The literal 1 is read as an exact integer whereas 1.0 or 1. is read as a floating point number.
Now the function / works on both exact an inexact numbers. If fed exact numbers it produces a fraction (which eventually ends up being printed in the repl).
That is you are not seeing the effect of a pretty printer, but the actual result. The algorithm works efficiently only on floating point numbers as input so you can consider adding a call to exact->inexact to your function.
As the other answers explain, it turned out this isn't actually about pretty printing.
However to answer you question literally (if you ever did want to disable pretty printing in racket-mode):
The Emacs variable is racket-pretty-print.
You can view documentation about it using C-h v.
To change it you can either:
Use Emacs' M-x customize UI.
Use (setq racket-pretty-print nil) in your Emacs init file, for example in a racket-repl-mode-hook.
This is actually intentional and is part of the Scheme standard (R5RS, R7RS). It is not restricted to Racket but should be the output of any Scheme interpreter/REPL. It has nothing to do with pretty printing. It is mostly considered a good thing since it is giving you the exact number (rational number) rather than a floating point approximation. If you do want the floating point result then do request it by using 1.0 rather than 1 etc.
> (/ 1.0 3)
0.3333333333333333
Alternatively, you can use the exact->inexact function e.g.
> (exact->inexact 1/3)
0.3333333333333333
Related
I am working on a Scheme program, where I need at some place a pair of a floatingpoint counter and the same counter as formated string. I am having issues with the number to string conversion.
Can someone explain me these inaccuracies in this code ?
(letrec ((ground-loop (lambda (times count step)
(if (= times 250)
(begin
(display "exit")
(newline)
)
(begin
(display (* times step)) (newline)
(display (number->string (* times step)))(newline)
(newline)
(newline)
(ground-loop (+ times 1) (* times step) step)
)
)
)
))
(ground-loop 0 0 0.05)
)
Part of the output looks like that
7.25
7.25
7.3
7.300000000000001
7.35
7.350000000000001
7.4
7.4
7.45
7.45
7.5
7.5
7.55
7.550000000000001
7.6
7.600000000000001
7.65
7.65
I am aware of floating point inaccuracies and tried several forms of increasing the counter but the issue is in the conversion itself.
Any ideas for an easy fix? Tried a bit with explicitly rounded numbers but this did not do the job. The results even vary from IDE and environment to environment. Do I really have to do string manipulation after conversion?
The very weird thing in my case is having an exact numeric result but the string is off.
Thank you
It looks to me as if:
the native float type (the type you get by reading 1.0) of your implementation is IEEE double float;
the display of your Scheme is not printing such floats 'correctly' (see below, I'm no sure this means it's buggy);
your number->string is doing the right thing.
By 'correctly' above I mean 'in a way so that reading what display printed returns an equivalent number'. I am not at all sure that display is required to be correct in this restrictive sense however, so I am not sure whether it's a bug. Someone who understands the Scheme standards better than I do might be able to comment on that.
In particular if the native float type of the languageis an IEEE double float, then, for instance:
(= (* 0.05 3) 0.15)
is false, as is
(= (* 0.05 146) 7.3)
Which is the example you have in the first line of your output.
So you certainly should not assume that your program will ever produce a number equal to the number you get by reading 7.3 for instance, because it won't.
In the above I have carefully avoided printing the numbers out, and that's because I'm not sure display is reliable on this, and in particular I'm not sure your display is reliable or that it is required to be.
Well, I have a Lisp implementation to hand which is reliable about this. In this system the default float format is a single-precision IEEE float, and I can get the reader to read double floats with, for instance 1.0d0. So, in this implementation you can see the results:
> (* 0.05d0 3)
0.15000000000000002D0
> (* 0.05d0 146)
7.300000000000001D0
And you'll see that these are exactly (up to the double-precision indicator) what number->string is giving you and not what display is giving you.
If what you want to do is to get a representation of the number in such a way that reading it will return an equivalent number, then number->string is what you should trust. In particular R5RS says in section 6.2.6 that:
(let ((number number)
(radix radix))
(eqv? number
(string->number (number->string number
radix)
radix)))
is true, and 'it is an error if no possible result makes this expression true'.
You can check the behaviour of number->float & float->number over a range of numbers by, for instance (this may assume a more recent or featurefull Scheme than you have):
(define (verify-float-conversion base times)
(define (good? f)
(eqv? (string->number (number->string f)) f))
(let loop ([i 0]
[bads '()])
(let ([c (* base i)])
(if (>= i times)
(values (null? bads) (reverse bads))
(loop (+ i 1) (if (good? c) bads (cons c bads)))))))
Then you should get
> (verify-float-conversion 0.05 10000)
#t
()
More generally using floats, still more floats that are the result of some computation more complicated than reading them some input source, as unique indices into any kind of tabular structure is fraught with danger to put it rather mildly: floating-point errors mean that it's just really dangerous to assume that (= a b) is true for floats even when it mathematically should be.
If you want such indices do exact arithmetic instead, and convert the results of that arithmetic to floats at the point you need to do computations. I believe (but am not sure) that Scheme implementations are nowadays required to support exact rational arithmetic (certainly this seems to be true for R6RS), so if you want to count 20ths (say) you can do so by counting in units of 1/20, which is exact, and then constructing floats when you need them.
It's probably safe to compare floats in the case that if you are for instance comparing a float you got by taking some initial float value and multiplying it by a machine integer and comparing it with some earlier version of itself which you have read by string->number. But if the calculation your doing is more complicated than that you need to be quite careful.
I am reading a Gentle Introduction to Symbolic Computation and it asks this question. Basically, the previous content deals with making up bigger functions with small ones. (Like 2- will be made of two 1- (decrement operators for lisp))
So one of the questions is what are the two different ways to define a function HALF which returns one half of its input. I have been able to come up with the obvious one (dividing number by 2) but then get stuck. I was thinking of subtracting HALF of the number from itself to get half but then the first half also has to be calculated...(I don't think the author intended to introduce recursion so soon in the book, so I am most probably wrong).
So my question is what is the other way? And are there only two ways?
EDIT : Example HALF(5) gives 2.5
P.S - the book deals with teaching LISP of which I know nothing about but apparently has a specific bent towards using smaller blocks to build bigger ones, so please try to answer using that approach.
P.P.S - I found this so far, but it is on a completely different topic - How to define that float is half of the number?
Pdf of book available here - http://www.cs.cmu.edu/~dst/LispBook/book.pdf (ctrl+f "two different ways")
It's seems to be you are describing peano arithmetic. In practice it works the same way as doing computation with fluids using cups and buckets.
You add by taking cups from the source(s) to a target bucket until the source(s) is empty. Multiplication and division is just advanced adding and substraction. To halve you take from source to two buckets in alterations until the source is empty. Of course this will either do ceil or floor depending on what bucket you choose to use as answer.
(defun halve (x)
;; make an auxillary procedure to do the job
(labels ((loop (x even acc)
(if (zerop x)
(if even (+ acc 0.5) acc)
(loop (- x 1) (not even) (if even (+ acc 1) acc)))))
;; use the auxillary procedure
(loop x nil 0)))
Originally i provided a Scheme version (since you just tagged lisp)
(define (halve x)
(let loop ((x x) (even #f) (acc 0))
(if (zero? x)
(if even (+ acc 0.5) acc)
(loop (- x 1) (not even) (if even (+ acc 1) acc)))))
Edit: Okay, lets see if I can describe this step by step. I'll break the function into multiple lines also.
(defun half (n)
;Takes integer n, returns half of n
(+
(ash n -1) ;Line A
(if (= (mod n 2) 1) .5 0))) ;Line B
So this whole function is an addition problem. It is simply adding two numbers, but to calculate the values of those two numbers requires additional function calls within the "+" function.
Line A: This performs a bit-shift on n. The -1 tells the function to shift n to the right one bit. To explain this we'll have to look at bit strings.
Suppose we have the number 8, represented in binary. Then we shift it one to the right.
1000| --> 100|0
The vertical bar is the end of the number. When we shift one to the right, the rightmost bit pops off and is not part of the number, leaving us with 100. This is the binary for 4.
We get the same value, however if we perform the shift on nine:
1001| --> 100|1
Once, again we get the value 4. We can see from this example that bit-shifting truncates the value and we need some way to account for the lost .5 on odd numbers, which is where Line B comes in.
Line B: First this line tests to see if n is even or odd. It does this by using the modulus operation, which returns the remainder of a division problem. In our case, the function call is (mod n 2), which returns the remainder of n divided by 2. If n is even, this will return 0, if it is odd, it will return 1.
Something that might be tripping you up is the lisp "=" function. It takes a conditional as its first parameter. The next parameter is the value the "=" function returns if the conditional is true, and the final parameter is what to return if the conditional is false.
So, in this case, we test to see if (mod n 2) is equal to one, which means we are testing to see if n is odd. If it is odd, we add .5 to our value from Line A, if it is not odd, we add nothing (0) to our value from Line A.
If I write this function in emacs-lisp:
(defun factorial (n)
(if (<= n 1)
1
(* n (factorial (- n 1)))))
=> factorial
It works well for small numbers like 5 or 10, but if I try and calculate (factorial 33) the answer is -1211487723752259584 which is obviously wrong, all large numbers break the function. In python this doesn't happen. What is causing this problem?
You can always invoke Emacs' calc library when dealing with large numbers.
(defun factorial (n)
(string-to-number (factorial--1 n)))
(defun factorial--1 (n)
(if (<= n 1)
"1"
(calc-eval (format "%s * %s"
(number-to-string n)
(factorial--1 (- n 1))))))
ELISP> (factorial 33)
8.683317618811886e+036
Further reading:
http://www.masteringemacs.org/articles/2012/04/25/fun-emacs-calc/
C-hig (calc) RET
C-hig (calc) Calling Calc from Your Programs RET
Integers have a specific range. Values outside this range can't be represented. This is pretty standard across most -- but not all -- programming languages. You can find the largest number Emacs Lisp's integer datatype can handle on your computer by checking the value of most-positive-fixnum.
Go to your *scratch* buffer -- or any Lisp buffer -- and type in most-positive-fixnum. Put the cursor at the end, then press C-x C-e. On my computer, I get 2305843009213693951 as the value. Yours might differ: I'm on a 64 bit machine, and this number is about 2^61. The solution to the factorial of 33 is 8683317618811886495518194401280000000. That's about 2^86, which is also more than my Emacs can handle. (I used Arc to calculate it exactly, because Arc can represent any size integer, subject to boring things like the amount of memory you have installed).
The most simple solution seems to be Paul's one:
(defun factorial (n) (calc-eval (format "%s!" n)))
ELISP> (factorial 33)
8683317618811886495518194401280000000
However, I tried for fun, by another Calc way, without using calc-eval and string.
Because much more complex Emacs Lisp programs with Calc can be done in this way.
Calc's defmath and calcFunc- functions are so powerful within Emacs Lisp.
(defmath myFact (n) (string-to-number (format-number (calcFunc-fact n))))
ELISP> (calcFunc-myFact 33)
8.683317618811886e+36
I landed on this question searching for a quick and easy way to compute a factorial in Elisp, preferrably without implementing it.
From the other answers, I gather that it is:
(calc-eval "10!")
which is equivalent to
(calc-eval "fact(10)")
and which is as concise as, and more powerful than, redefining a factorial function. For instance, you can have a binomial coefficient this way:
(calc-eval "7!/3!(7-3)!")
or even that way:
(calc-eval "choose(7,3)")
Calc is really worth exploring. I suggest doing the interactive tutorial inside Emacs. You can launch it with C-x * t.
As for calc, you can use it with C-x * c, or with M-x calc.
I'm looking for the standard way to represent negative infinity in Lisp. Is there a symblic value which is recognised by Lisp's arithmetic functions as less than all other numbers?
Specifically, I'm looking for an elegant way to write the following:
(defun largest (lst)
"Evaluates to the largest number in lst"
(if (null lst)
***negative-inifinity***
(max (car lst) (largest (cdr lst)))))
ANSI Common Lisp has bignum, which can used to represent arbitrarily large numbers as long as you have enough space, but it doesn't specify an "infinity" value. Some implementations may, but that's not part of the standard.
In your case, I think you've got to rethink your approach based on the purpose of your function: finding the largest number in a list. Trying to find the largest number in an empty list is invalid/nonsense, though, so you want to provide for that case. So you can define a precondition, and if it's not met, return nil or raise an error. Which in fact is what the built-in function max does.
(apply #'max '(1 2 3 4)) => 4
(apply #'max nil) => error
EDIT: As pointed by Rainer Joswig, Common Lisp doesn't allow arbitrarily long argument lists, thus it is best to use reduce instead of apply.
(reduce #'max '(1 2 3 4))
There is nothing like that in ANSI Common Lisp. Common Lisp implementations (and even math applications) differ in their representation of negative infinity.
For example in LispWorks for double floats:
CL-USER 23 > (* MOST-NEGATIVE-DOUBLE-FLOAT 10)
-1D++0
I never really thought about this until I was explaining some clojure code to a coworker who wasn't familiar with clojure. I was explaining let to him when he asked why you use a vector to declare the bindings rather than a list. I didn't really have an answer for him. But the language does restrict you from using lists:
=> (let (x 1) x)
java.lang.IllegalArgumentException: let requires a vector for its binding (NO_SOURCE_FILE:0)
Why exactly is this?
Mostly readability, I imagine. Whenever bindings are needed in Clojure, a vector is pretty consistently used. A lot of people agree that vectors for bindings make things flow better, and make it easier to discern what the bindings are and what the running code is.
Just for fun:
user=> (defmacro list-let [bindings & body] `(let ~(vec bindings) ~#body))
#'user/list-let
user=> (macroexpand-1 '(list-let (x 0) (println x)))
(clojure.core/let [x 0] (println x))
user=> (list-let (x 0 y 1) (println x y))
0 1
nil
This is an idiom from Scheme. In many Scheme implementations, square brackets can be used interchangeably with round parentheses in list literals. In those Scheme implementations, square brackets are often used to distinguish parameter lists, argument lists and bindings from S-expressions or data lists.
In Clojure, parentheses and brackets mean different things, but they are used the same way in binding declarations.
Clojure tries very hard to be consistent. There is no technical reason with a list form could not have been used in let, fn, with-open, etc... In fact, you can create your own my-let easily enough that uses one instead. However, aside from standing out visibly, the vector is used consistently across forms to mean "here are some bindings". You should strive to uphold that ideal in your own code.
my guess is that it's a convention
fn used it, defn used it, loop uses.
it seems that it's for everything that resembles a block of code that has some parameters; more specific, the square brackets are for marking those parameters
other forms for blocks of code don't use it, like if or do. they don't have any parameters
Another way to think about this is that let is simply derived from lambda. These two expressions are equivalent:
((fn [y] (+ y 42)) 10)
(let [y 10] (+ 42 y))
So as an academic or instructional point, you could even write your own very rudimentary version of let that took a list as well as a vector:
(defmacro my-let [x body]
(list (list `fn[(first x)]
`~body)
(last x)))
(my-let (z 42) (* z z))
although there would be no practical reason to do this.