I have learning Common Lisp for 2 months, I meet a puzzle, here is the code:
CL-USER> (round 33.6)
34
-0.40000153
anyone explain it? Thanks
I'm not sure I understand your problem. In CLisp, round
rounds to the nearest integer (unless you specify a divisor). The nearest integer to 33.6
is 34
so that bit is right.
And since round
returns both the quotient and remainder, it gives 34
, with a remainder of -0.4
. That bit's mostly right so I suspect you're wondering why it's only "mostly".
The reason it's not exactly -0.4
is almost certainly due to the limited precision of floating point numbers. The result of calculating the difference between a (seemingly exact) floating point number and an integer can be surprising:
CL-USER> (- 23.6 24) -0.39999962
You'd expect in a perfect world for that to return -0.4
but it doesn't, for reasons mentioned above.
If you want to know why that's the case (i.e., how floating point works under the covers), you can check out this and this as examples.