Subject: | BigFloat new() on a BigRat object yields unexpected result |
Date: | Mon, 28 Dec 2015 15:06:31 -0700 |
To: | bug-math-bigint [...] rt.cpan.org |
From: | Glenn Golden <gdg [...] zplane.com> |
The attached annotated example shows some unexpected (to me) behavior of
Math::BigFloat->new(). On my setup (version info below), the output is:
perl: v5.22.0
BigFloat: 1.999710
BigRat: 0.2608
ref(x): Math::BigRat
ref(y): Math::BigRat
x: 42/43
y: 42/43
The underlying question that lead to this example is: Is there a clean way
to go about creating a BigFloat object that has the same mathematical value
as a given BigRat object? The only way I was able to make it work was to
create two BigFloats, one from the numerator and one from the denominator of
the BigRat, and then divide them. Works fine, just wondering if there's a
cleaner approach.
Show quoted text
--------------------------- cut here --------------------------------
use warnings;
use strict;
use Math::BigFloat;
use Math::BigRat;
print "perl: $^V\n";
print "BigFloat: $Math::BigFloat::VERSION\n";
print "BigRat: $Math::BigRat::VERSION\n";
print "\n";
my ($x, $y);
#
# Create $x as a BigRat.
#
$x = Math::BigRat->new('42/43');
if ($x->is_nan()) { die "x is nan"; } # No die(), as expected
#
# Now we want to create $y as a BigFloat having the same mathematical value
# as $x. Naively, we try this:
#
$y = Math::BigFloat->new($x);
#
# The above statement behaves as follows, both unexpected (to me):
#
# 1. The new($x) does not fail. I expected it to fail since, according to
# the BigFloat man page ("Input" subsection) the input to new() is
# neither "...a BigFloat object nor a string of any of the following
# forms."
#
# 2. The resulting $y winds up as a BigRat.
#
if ($y->is_nan()) { die "y is nan"; } # Does not die(). [unexpected]
print "ref(x): " . ref($x) . "\n"; # Reports $x as BigRat as expected
print "ref(y): " . ref($y) . "\n"; # Reports $y as BigRat: [unexpected]
print "x: $x\n"; # Prints "42/43"
print "y: $y\n"; # Prints "42/43"
---------------------------------------------------------------------