Subject: | behaivior of division by zero |
I want to change the behavior of division by zero, likes follow.
Show quoted text
>>
including division by zero, has a well-defined result. In IEEE 754
arithmetic, a รท 0 is positive infinity when a is positive, negative
infinity when a is negative, and NaN (not a number) when a = 0.
http://en.wikipedia.org/wiki/Division_by_zero#Division_by_zero_in_computer_arithmetic
<<
I think, XML::XPath cannot use valid substring() function by current
op_div implementation.
follow is a patch.
=== t/33op_div.t
==================================================================
--- t/33op_div.t (revision 7247)
+++ t/33op_div.t (local)
@@ -0,0 +1,15 @@
+use strict;
+use warnings;
+use Test::More tests => 5;
+use XML::XPath;
+
+my $xp = XML::XPath->new(ioref => *DATA);
+ok($xp);
+
+is $xp->findvalue('4 div 2'), 2;
+is $xp->findvalue('4 div 0'), 'Infinity';
+is $xp->findvalue('-4 div 0'), '-Infinity';
+is $xp->findvalue('0 div 0'), 'NaN';
+
+__END__
+<p></p>
=== XPath/Expr.pm
==================================================================
--- XPath/Expr.pm (revision 7247)
+++ XPath/Expr.pm (local)
@@ -508,18 +508,26 @@
my $lh_results = $lhs->evaluate($node);
my $rh_results = $rhs->evaluate($node);
+ # handle zero devided cases.
+ if ($rh_results->to_number->value == 0) {
+ my $lv = $lh_results->to_number->value;
+ if ($lv == 0) {
+ return XML::XPath::Literal->new('NaN');
+ } elsif ($lv > 0) {
+ return XML::XPath::Literal->new('Infinity');
+ } elsif ($lv < 0) {
+ return XML::XPath::Literal->new('-Infinity');
+ } else {
+ die "CAN'T REACH HERE";
+ }
+ }
+
my $result = eval {
$lh_results->to_number->value
/
$rh_results->to_number->value
;
};
- if ($@) {
- # assume divide by zero
- # This is probably a terrible way to handle this!
- # Ah well... who wants to live forever...
- return XML::XPath::Literal->new('Infinity');
- }
return XML::XPath::Number->new($result);
}