iakobski has asked for the wisdom of the Perl Monks concerning the following question:

The documentation for Math::BigFloat says that zero is stored as 0E1 - presumably for the same reason as DBI returns 0E0. However, although the exponent() function does return 1, it still evaluates to false in a boolean context:

use Math::BigFloat; my $x = Math::BigFloat->bzero(); my $y = '0e+1'; print $/, "x is " , $x->bsstr(); print $/, "y is " , $y; print $/; print $/, "x + 0 is " , $x + 0; print $/, "y + 0 is " , $y + 0; print $/; print $/, "x is " , ( $x ) ? "true" : "false"; print $/, "y is " , ( $y ) ? "true" : "false"; print $/; print $/, "x eq 0e+1 is ", ( $x eq '0e+1' ) ? "true" : "false"; print $/, "y eq 0e+1 is ", ( $y eq '0e+1' ) ? "true" : "false"; print $/, "x eq y is ", ( $x eq $y ) ? "true" : "false"; C:\iakobski\perl>test1.pl x is 0e+1 y is 0e+1 x + 0 is 0 y + 0 is 0 x is false y is true x eq 0e+1 is false y eq 0e+1 is true x eq y is false

My questions: 1. Why? 2. Anyone know what this comment means in the docs:

"A zero is represented and returned as 0E1, not 0E0 (after Knuth)."

-- iakobski

Replies are listed 'Best First'.
Re: Math::BigFloat and zero
by JavaFan (Canon) on Sep 23, 2010 at 16:12 UTC
    I think you're assuming that "$x" equals $x->bsstr. It doesn't in this case. $x stringifies (and numifies) to "0", not to "0E1".

      Yes, that's exactly what it does.

      What I'm trying to work out is why it stores 0 as '0E1' if it stringifies to '0'? DBI functions return zero as '0E0' so that it becomes 'true' in a boolean context, but if you evaluate a Math::BigFloat zero in a boolean context it becomes 'false'. So why not just store it internally as '0'? What is gained by storing as '0E1'?

      My second question is why use '0E1' instead of the more usual '0E0'? They both become 0 in a numerical context and stringify to '0'.

      -- iakobski

        Well, Math::BigFloat is about floating point numbers. Not about integers. So, to me it makes a lot of sense to store it as a significant/exponent pair, and not a plain integer. Note that the internal representation is not "0E1". The internal representation is:
        { _e => 1, _es => '+', _m => [0], sign => '+', }
        which corresponds to 0E1.
        Did you try looking up Knuth's reasoning?