On Wed, Sep 1, 2010 at 17:32, Jim <j...@lowcarbfriends.com> wrote:
> On 9/1/2010 5:04 PM, Chas. Owens wrote:
>>
>> On Wed, Sep 1, 2010 at 16:46, Jim<j...@lowcarbfriends.com>  wrote:
>>>
>>> Can anyone comment how they handle floating point precision situations
>>> like
>>> this?
>>
>> snip
>>>
>>> I don't like either of these solutions.
>>>
>>> How do others deal with this?
>>
>> snip
>>
>> Short answer: floating point numbers suck, but are fast.  If you need
>> accuracy you should convert your numbers into integers (for instance,
>> financial programs tend to use fractions of a penny, so 1000 is one
>> cent) or move to a slower but exact math system like
>> [Math::Currency][0] (note, this is not an endorsement of that module,
>> I have never used it).
>>
>>  [0]:
>> http://search.cpan.org/~jpeacock/Math-Currency-0.47/lib/Math/Currency.pm
>>
>>
>
> Thanks... that's the sort of answer I've been reading about... not crazy
> about it... but it is what it is. This problem is more infuriating than
> unsolvable in terms of why I need to even think about something like this.
> My $0.99 calculator can computer those numbers precisely, but my $3000
> server can't.
>

Well, I call bullshit on that.  You calculator probably has the same
crappy IEEE 754 floating point implementation as everything else, it
is just rounding the output so you don't notice it and you never push
a crappy calculator they way you do a $3000 server.  The problem is a
simple one: some numbers can't be represented.  I am not even talking
about weird ones like pi.  Simple numbers like .1 cannot be
represented by floating point numbers:

perl -e 'printf "%32.32f\n%32.32f\n", .5 - .4, .1'
0.09999999999999997779553950749687
0.10000000000000000555111512312578

The problem is not unique to Perl 5, it is inherent in floating point numbers:

#include <stdio.h>

int main(int argc, char** argv) {
        printf("%32.32f\n%32.32f\n", .5 - .4, .1);
        return 0;
}

0.09999999999999997779553950749687
0.10000000000000000555111512312578

If you are willing to live with rounding you can make the problem
harder to see, but it is still there.

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to