… you know something about Floating-Point Arithmetic and if you use Common Lisp. :-)
Background: recent story that appeared on reddit. From time to time there is always an article about this issue. I am surprised by the amount of people who simply are unaware of it or who don’t care. And it’s not just someone who started to learn, which is a bit worrying. This particular example also reminds me of one of the many things that I like about Common Lisp: well-integrated rational arithmetic. So, if you code in Common Lisp the given C function taking into account rationals:
(defun f (n) (let ((a (/ (floor (* n 10)) 10))) (- a (/ (- (* a 10) 10) 10))))
And now you run for all the test cases presented in the article:
CL-USER> (defparameter *numbers* '(5.1 91.3 451.9 7341.4 51367.7 897451.7 1923556.4 59567771.9 176498634.7 2399851001.7 60098761442.7 772555211114.1 1209983553611.9 59871426773404.9 190776306245331.2 2987154209766221.6 19843566622234755.9 719525522284533115.3 8399871243556765103.9 39847765103525225199.1 553774558711019983333.9)) *NUMBERS* CL-USER> (loop for n in *numbers* collect (f n)) (1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1)
Et voilá! The answer is always 1. Naturally, if you code the function just like in the C version, you will get the same type of results as in the story. But then, why would you want to do that? :-)