On 09/12/2012 10:25 PM, Alastair Irving wrote:
On 12/09/2012 15:14, P Purkayastha wrote:
Can anyone point out what is wrong with this comparison:
sage: 0.2 + 0.1 == 0.3
False
It seems baffling that something as simple as this returns False.
Its a fairly common problem with doing arithmetic with floatingpoint
numbers as they are only storred to some finite precision and the binary
expansion could be infinite. In particular note that 0.2+0.1-0.3 returns
something very small but non-zero.
Alastair
I agree with all the replies about storage of floating point numbers.
This was brought up by a student doing MATLAB and I see the same problem
in octave and Sage. In MATLAB, teh only exception was at 0.3, whereas in
octave and Sage there are many more exceptions.
In octave:
octave:1> l = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9];
octave:3> i=1; for x=0.1:0.1:0.9, disp(['case ' num2str(l(i)) ': '
num2str(l(i) == x)]); i=i+1; end
case 0.1: 1
case 0.2: 1
case 0.3: 0
case 0.4: 1
case 0.5: 1
case 0.6: 1
case 0.7: 0
case 0.8: 1
case 0.9: 1
In sage:
sage: l = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
sage: for i,x in enumerate(srange(0.1, 1.0, 0.1)): print "case {0}:
{1}".format(l[i], l[i] == x)
....:
case 0.100000000000000: True
case 0.200000000000000: True
case 0.300000000000000: False
case 0.400000000000000: True
case 0.500000000000000: True
case 0.600000000000000: True
case 0.700000000000000: True
case 0.800000000000000: False
case 0.900000000000000: False
But it seems fine in mathematica (at least on wolframalpha):
http://www.wolframalpha.com/input/?i=0.3+%3D%3D+0.1+%2B+0.1+%2B+0.1
--
You received this message because you are subscribed to the Google Groups
"sage-support" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
Visit this group at http://groups.google.com/group/sage-support?hl=en.