Gambit scheme incorrect calculation for numbers with decimals - scheme

i'm using gambit-c intepreter to evaluate scheme arithmetic operations, but it's results are bit off. for example i execute (+ 23 20.01) and it gives me 43.010000000000005, instead of 43.01.
This only occurs if i use numbers with 2 decimal points.
Is there a fix for this?

It has to do with how floating point calculations are done. Please read What Every Programmer Should Know About Floating-Point Arithmetic.
You are in luck! In Scheme you fix this by using exact numbers:
(+ 23 #e20.01) ; ==> 4301/100
You can make it inexact with:
(exact->inexact (+ 23 #e20.01)) ; ==> 43.01

Related

Passing a list to a multiple-arity function in DrRacket (Scheme)

I am trying to generate the least common multiple for all numbers from 1 to n as described in OEIS-A003418. In the DrRacket REPL I'm using the following code:
(lcm (apply values (build-list 256 add1)))
Which gives me a "result arity mismatch" error (expected 1, received 256). When I omit lcm I get a sequence from 1 to 256 output to the console. I'm uncertain as to the cause of the arity mismatch, since lcm is supposed to be able to take arbitrarily many arguments (according to the docs), and apply seems to be doing what I would expect when it is the outermost function and not an input to lcm. What am I missing? Also, if there is an easier way to write the LCM from 1 to n please feel free to share.
There is no difference between fixed arity and non-fixed arity when you use apply:
(apply lcm (build-list 256 add1))

Whole fraction numbers in Scheme

Is there an easy way to display whole rational numbers for example:
(average '(1 2 3 4)) ;returns 2 1/2
I would like it to return 5/2. Thank you.
This is DrRacket-specific behavior. It customizes the Racket print handler to print out certain values in "pretty" ways, some of which aren't even plain text. For example, DrRacket will print images as pictures in the REPL, and it will print syntax objects as fully interactive widgets that display source information along with the datum structure.
Racket reserves the print function to be customized, and it doesn't guarantee the output of such a function. If you want consistent output, use write, which will always produce plain text unless explicitly altered by the programmer.
(write (/ 5 2)) ; => 5/2
Note that in the REPL, print will use the same textual representation that write uses for exact, rational numbers.
You can use numerator and denominator to get the pieces you want. Something like:
(let* ((avg (average '(1 2 3 4)))
(num (numerator avg))
(den (denominator avg)))
(printf "~a/~a~n" num den)))

Strange behavior with the lisp random function

Is there anyone can explain to me the following behavior concerning the random function with the float numbers and how to get rid of this:
CL-USER> (loop for i from 1 to 20 collect (* 0.1 (random 100)))
;; with sbcl ...
(9.2 4.4 9.5 0.5 9.7 5.8 4.3 9.900001 3.7 6.8 2.6000001 9.5 1.6 8.900001 3.3 1.7 5.1 5.5 4.2000003 8.2)
;; with closure ...
(7.7000003 7.2000003 1.7 5.6 7.5 2.2 5.0 7.6 2.0 4.9 2.9 1.6 0.4 6.1 3.3 7.1 8.7 6.5 5.6 9.2)
That is totally expected and appropriate in the context of floating point numbers. It is the same in every other language.
Binary floating point numbers (as defined by IEEE) cannot represent all decimal fractions exactly. For example, the decimal fraction 0.2 in binary is 0.0011001100110011...., so you cannot represent it exactly with a finite amount of bits. Therefore, many floating point numbers necessarily are rounded. If you add them up then, the rounding errors accumulate. Sometimes they cancel each other out, sometimes not. If you multiply them (as you did), they multiply.
If you want to have the exact fractions, Common Lisp offers you to work with rationals. For example, if you calculate (/ 1 5), you get 1/5, which is the printed representation of such a rational number, and this is exact (internally, the calculation works on the numerator and denominator). You can calculate with these exact numbers:
CL-USER> (+ 1/5 2/3)
13/15
CL-USER> (+ 3/5 2/5)
1
In order to print them out as decimal fractions, you can use the format control ~f, for example:
CL-USER> (format t "~,3f" 13/15)
0.867
What's the strange behavior?
Are you worried that, for example, 0.1 * 99 seems to be 9.90001? That's normal for floating point numbers. They're inexact. They sacrifice exactness to get range. You cannot expect to get something without giving something up.
If you want rational numbers, don't use floats...
(loop for i from 1 to 20 collect (/ (random 100) 10))
(loop for i from 1 to 20 collect (read-from-string (format nil "~v$" 1 (/ (random 100) 10))))

MIT-Scheme: Different Behavior on Infinite Loop Depending on Numbers

I was working on the solution of the exercise 1.6 of the SICP book when I saw two different behaviors when I run the code depending on the numbers that I used.
If I use natural numbers when I call the sqrt-iter procedure the interpreter just never stop but when I force the decimal division using float-point numbers the interpreter responds: Aborting!: maximum recursion depth exceeded.
Does anyone know the reason for the different behavior?
I made a gist with my answer to help anyone that wants to run the code, just copy & paste: http://bit.ly/Qv1wru. The mit-scheme version is 9.1.1.
Your good-enough? procedure seems wrong, try with this one:
(define (good-enough? guess x)
(< (abs (- (sqr guess) x)) 0.001))

Finding if a number is the power of 2 in Scheme

I'm fairly new to Scheme and am attempting to learn it on my own from scratch. I'm stuck on the syntax of this problem. I know that if I want to find out if a number is a power of 2, in C for instance, I would simply do:
return (x & (x - 1)) == 0;
which would return true or false. How would I be able to convert this into a couple simple lines in Scheme?
I'll give you a hint since you're trying to learn the language.
Scheme has a function called (bitwise-and ...) which is equivalent to the & operator in C (there is also (bitwise-xor ...), (bitwise-not ..), etc., which do the expected thing).
(Here is the documentation of the (bitwise-and ...) function)
Given that, would you be able to translate what you've written in your question into Scheme code?
N.B: For a problem like this, you really don't need to resort to bitwise operations when using Scheme. Realistically, you should be writing a (possibly probably tail) recursive function that will compute this for you.
You can do this using a built in bitwise operator.
(define (pow2? x)
(= (bitwise-and x (- x 1))
0))
Scheme also has biwise operators.
But if you really want to develop your scheme skills, you should write a function that decides if an integer is a power of 2 by recursively dividing it by 2 until you are left with either 2 or with an odd number. This would be very inefficient, but really cool nonetheless.

Resources