Merge pull request #175 from dotjrich/issue-136

Handle NaN and infinity values
This commit is contained in:
Michael Hansen
2020-10-15 19:19:55 -07:00
committed by GitHub
5 changed files with 37 additions and 1 deletions

View File

@@ -1,5 +1,6 @@
#include "pyc_numeric.h"
#include "bytecode.h"
#include <cmath>
#ifdef _MSC_VER
#define snprintf _snprintf
@@ -268,7 +269,26 @@ void print_const(PycRef<PycObject> obj, PycModule* mod)
obj.cast<PycComplex>()->imag());
break;
case PycObject::TYPE_BINARY_FLOAT:
fprintf(pyc_output, "%g", obj.cast<PycCFloat>()->value());
{
// Wrap any nan/inf values in float('').
double value = obj.cast<PycCFloat>()->value();
bool is_negative = std::signbit(value);
if (std::isnan(value)) {
if (is_negative) {
fprintf(pyc_output, "float('-nan')");
} else {
fprintf(pyc_output, "float('nan')");
}
} else if (std::isinf(value)) {
if (is_negative) {
fprintf(pyc_output, "float('-inf')");
} else {
fprintf(pyc_output, "float('inf')");
}
} else {
fprintf(pyc_output, "%g", value);
}
}
break;
case PycObject::TYPE_BINARY_COMPLEX:
fprintf(pyc_output, "(%g+%gj)", obj.cast<PycCComplex>()->value(),

Binary file not shown.

Binary file not shown.

8
tests/input/nan_inf.py Normal file
View File

@@ -0,0 +1,8 @@
a = 1e300 * 1e300 * 0
b = -1e300 * 1e300 * 0
c = 1e300 * 1e300
d = -1e300 * 1e300
e = float('nan')
f = float('-nan')
g = float('inf')
h = float('-inf')

View File

@@ -0,0 +1,8 @@
a = float ( '-nan' ) <EOL>
b = float ( '-nan' ) <EOL>
c = float ( 'inf' ) <EOL>
d = float ( '-inf' ) <EOL>
e = float ( 'nan' ) <EOL>
f = float ( '-nan' ) <EOL>
g = float ( 'inf' ) <EOL>
h = float ( '-inf' ) <EOL>