Gentoo Archives: gentoo-user

From: Paul Colquhoun <paulcol@×××××××××××××××××.au>
To: gentoo-user@l.g.o
Subject: Re: [gentoo-user] 69.99 != 69.99
Date: Sun, 23 Aug 2015 01:14:51
Message-Id: 3981511.bsdFisGKMY@bluering
In Reply to: Re: [gentoo-user] 69.99 != 69.99 by hw
1 On Sat, 22 Aug 2015 16:57:41 hw wrote:
2 > Am 22.08.2015 um 15:43 schrieb Alan McKinnon:
3 > > On 22/08/2015 15:26, hw wrote:
4 > >> Hi,
5 > >>
6 > >> I have the following in a perl script:
7 > >> if ($a != $b) {
8 > >>
9 > >> print "e: '$a', t: '$b'\n";
10 > >>
11 > >> }
12 > >>
13 > >> That will print:
14 > >>
15 > >> e: '69.99', t: '69.99'
16 > >>
17 > >>
18 > >> When I replace != with ne (if ($a ne $a) {), it doesn't print.
19 > >>
20 > >>
21 > >> Is that a bug or a feature? And if it's a feature, what's the
22 > >> explanation?
23
24
25 > > != does a numerical comparison. More on this below
26 > > ne does a string comparison. When viewed as a bunch of
27 characters, 69.99
28 > > and 69.99 are identical.
29
30 > > Now, your comparisons are NOT random. They are entirely
31 predictable, as
32 > > long as you know what is going on; you are running into floating
33 point
34 > > numbers. And as it turns out, computers never represent these
35 things
36 > > exactly (they are NOT integers). Even though they look identical
37 > > on-screen, in RAM they will not be (this must be so for perl to do the
38 > > print). Maybe they actually resolve to 69.990000001 and
39 69.99000000. You
40 > > see them as close-as-dammit equal, perl sees them as entirely
41 different.
42 >
43 > Why can't it print the number as it is, or at least as it is compared,
44 > like it should? If it would, one could see at once what the problem is.
45
46
47 Your print values are coming from the original variables. The numeric
48 comparison does an internal conversion to two temporary variables,
49 and compares those, WITHOUT affecting the original data.
50
51 This string to float conversion appears not to be deterministic, if it
52 converts two identical strings into two different float values, but I don't
53 know enough about the internals to comment any further.
54
55
56 --
57 Reverend Paul Colquhoun, ULC. http://andor.dropbear.id.au/
58 Asking for technical help in newsgroups? Read this first:
59 http://catb.org/~esr/faqs/smart-questions.html#intro