1 |
On 22/08/2015 17:38, Alexander Kapshuk wrote: |
2 |
> On Sat, Aug 22, 2015 at 4:26 PM, hw <hw@×××××××××××××××××××××.de> wrote: |
3 |
>> |
4 |
>> Hi, |
5 |
>> |
6 |
>> I have the following in a perl script: |
7 |
>> |
8 |
>> |
9 |
>> if ($a != $b) { |
10 |
>> print "e: '$a', t: '$b'\n"; |
11 |
>> } |
12 |
>> |
13 |
>> |
14 |
>> That will print: |
15 |
>> |
16 |
>> e: '69.99', t: '69.99' |
17 |
>> |
18 |
>> |
19 |
>> When I replace != with ne (if ($a ne $a) {), it doesn't print. |
20 |
>> |
21 |
>> |
22 |
>> Is that a bug or a feature? And if it's a feature, what's the explanation? |
23 |
>> |
24 |
>> And how do you deal with comparisions of variables when you get randomly |
25 |
>> either correct results or wrong ones? It's randomly because this statement |
26 |
>> checks multiple values in the script, and 69.99 is the only number showing |
27 |
>> up yet which isn't numerically equal to itself (but equal to itself when |
28 |
>> compared as strings). |
29 |
>> |
30 |
> |
31 |
> Perl Cookbook, 2nd edition, suggests these two approaches to comparing |
32 |
> floats for equality. |
33 |
> (1). Use sprintf to format the numbers to a certain number of decimal |
34 |
> places, then compare the resulting strings. |
35 |
> (2). Alternatively, store the numbers as integers by assuming the decimal place. |
36 |
|
37 |
|
38 |
A good way to demonstrate just how problematic floats can be is to point |
39 |
out that floats are banned in the linux kernel for exactly this reason. |
40 |
Integers only. |
41 |
|
42 |
|
43 |
-- |
44 |
Alan McKinnon |
45 |
alan.mckinnon@×××××.com |