Strange floating-point behaviour in Python
At work, I - sadly - am limited to Windows for my 3D mechanical design work.
Every now and then, I have to do some basic math with a calculator but sometimes it is much easier to do things in one, long mathematical expression and have it evaluated (with proper bracketing). I installed Python on my Window XP workstation, and I noticed something VERY strange when I did a simple calculation (let's just say this boils down to laziness): Code:
>>> (11.175 - 3) / 2 I got somewhat upset and installed "Lisp in a Box" (oh darn, eh?) and did the exact same calculation: Code:
CL-USER> (/ (- 11.175 3) 2) |
What about this?
Code:
>>> 0.1 |
Thanks for the reply, and the link, colucix! :)
However, I am still left with a feeling of, "Why isn't this fixable? Why is it CLISP doesn't do that, and Python does?" |
Maybe because of the different method to convert numbers to string upon displaying on the terminal. The following should give the expected number, since the str function consider only 12 significant digits
Code:
>>> print str((11.175 - 3) / 2) |
If you think that was cool try running a program to calculate factorials. I couldn't believe how fast common lisp could get the result in 100s of digits!
Note to self: learn Lisp! |
:) It's a beautiful language.
Again, thank you for your responses colucix. |
Interesting. It is well known that certain rational figures (are they called like this in English as well) cannot be represented in binary as they are represented in decimal, with a finite number of bits.
However, can someone explain this? Code:
donald_pc:/tmp$ echo "64 k 11.175 3 - 2 / p" | dc It is really not cheating! Code:
donald_pc:/tmp$ echo "64 k 11.175000000000000000000000000000000000000000000000001 3 - 2 / p" | dc The most amazing is, I can invert the operation with the result I got, and then the outcome is exactly the number I started with. Is there something really smart going on? jlinkels |
All times are GMT -5. The time now is 05:04 PM. |