1

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

Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
  • 1
    Also see [*What Every Computer Scientist Should Know About Floating-Point Arithmetic*, by David Goldberg](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – Joshua Taylor Mar 06 '14 at 13:04
  • 1
    Also see [Mysterious problem with floating point in LISP - time axis generation](http://stackoverflow.com/q/6225211/1281433), [exp in SBCL is wrong?](http://stackoverflow.com/q/4771346/1281433), [Floating Point Precision Error](http://stackoverflow.com/q/20490115/1281433), [(Racket/Scheme) Subtraction yields result off by incredibly small margin](http://stackoverflow.com/q/13693041/1281433), [Why in Common Lisp, when I run the function “acos” with an argument of 1, is the answer is wrong?](http://stackoverflow.com/q/17424545/1281433), … – Joshua Taylor Mar 06 '14 at 13:07

1 Answers1

4

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.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953