简体   繁体   中英

Why round is incorrect in CCL?

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 (ie, how floating point works under the covers), you can check out this and this as examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM