Re: another newbie question
On Jul 22, 2005, at 2:56 AM, Carlos Bruguera wrote:
> Hello guys... I need to finish my genethic algorithm today and i found
> some little problem, I'm doing:
>
> (+ (* 2 0.0001) 4.1)
>
> my interpreter prints this:
> 4.1001997
>
> Why??? shouldn't it be just 4.1002 ?
> if If substitute 4.1 for 3.1 it prints the correct result, but for
> 4.1, 5.1, 6.1 it screws it up.
>
> I'm desperate, i need to finish this quick :(
It is doing the right thing, just not what you want. As others have
pointed out, floating point numbers are approximations (any numerical
analysis book will cover this in detail) and using them will result in
approximate results. To illustrate (it is nice to have CL around to see
this kind of stuff):
(list (+ (* 2 0.0001) 4.1)
(+ ( * 2 1/10000) 41/10)
(float (+ ( * 2 1/10000) 41/10))
(rational 4.1)
(+ (* 2 (rational 0.0001)) (rational 4.1))
(float (+ (* 2 (rational 0.0001)) (rational 4.1))))
produces:
(4.1001997 20501/5000 4.1002 8598323/2097152 281763591959/68719476736
4.1001997)
The trouble begins when you let the lisp reader handle the '4.1'.
And, if you control the display of the number:
(format nil "~,4f" (+ (* 2 0.0001) 4.1)) --> "4.1002"
and, just for fun:
(format nil "~,4f" (+ ( * 2 1/10000) 41/10)) --> "4.1002"
The error is in the 7th decimal place, do you really care about that,
and if so why? The 'why' will help you decide between ignoring the
issue, controlling the display of numbers, increasing the precision of
the floats to double or long, using rational numbers instead,
controlling errors, changing algorithms, or some other even more
desperate measure.
----
Bob Hutchison -- blogs at <http://www.recursive.ca/hutch/>
Recursive Design Inc. -- <http://www.recursive.ca/>