shithub: mc

Download patch

ref: 2fd5ae3c5599fdd067ed11f3a58fb03da587db28
parent: fd00fa796bd36d2d369ff2ac67ac2a35d981ea6c
author: S. Gilles <sgilles@math.umd.edu>
date: Mon Apr 29 04:35:17 EDT 2019

Print "NaN" and "Inf" for floating-point NaNs and infinites.

--- a/lib/std/fltfmt.myr
+++ b/lib/std/fltfmt.myr
@@ -24,7 +24,22 @@
 const flt64bfmt = {sb, val, mode, precision
 	var isneg, exp, mant
 
+	if isnan(val)
+		sbputs(sb, "NaN")
+		-> void
+	;;
+
 	(isneg, exp, mant) = flt64explode(val)
+
+	if exp > Dblbias
+		if isneg
+			std.sbputs(sb, "-Inf")
+		else
+			std.sbputs(sb, "Inf")
+		;;
+		-> void
+	;;
+
 	exp = max(exp, 1 - Dblbias)
 	dragon4(sb, isneg, mant, exp - 52, Dblbias, mode, precision)
 }
@@ -32,7 +47,22 @@
 const flt32bfmt = {sb, val, mode, precision
 	var isneg, exp, mant
 
+	if isnan(val)
+		sbputs(sb, "NaN")
+		-> void
+	;;
+
 	(isneg, exp, mant) = flt32explode(val)
+
+	if (exp : int64) > Fltbias
+		if isneg
+			std.sbputs(sb, "-Inf")
+		else
+			std.sbputs(sb, "Inf")
+		;;
+		-> void
+	;;
+
 	exp = (max((exp : int64), 1 - Fltbias) : int32)
 	dragon4(sb, isneg, (mant : uint64), (exp - 23 : int64), Fltbias, mode, precision)
 }
--- /dev/null
+++ b/lib/std/test/fltfmt.myr
@@ -1,0 +1,38 @@
+use std
+use testr
+use math
+
+const main = {
+	math.fptrap(false)
+	testr.run([
+		[.name = "put0", .fn = put0],
+		[.name = "putNaN", .fn = putNaN],
+		[.name = "putInf", .fn = putInf],
+	][:])
+}
+
+const put0 = {c
+        var f : flt32 = 0.0
+        var g : flt64 = 0.0
+	testr.check(c, std.eq(std.fmt("f is {}", f), "f is 0.0"), "0.0 should format to \"0.0\"")
+	testr.check(c, std.eq(std.fmt("g is {}", g), "g is 0.0"), "0.0 should format to \"0.0\"")
+}
+
+const putNaN = {c
+        var f : flt32 = std.flt32nan()
+        var g : flt64 = std.flt64nan()
+        var f2 : flt32 = std.flt32frombits(0x7fc00ab0)
+        var g2 : flt64 = std.flt64frombits(0x7ff800000000abc0)
+	testr.check(c, std.eq(std.fmt("f is {}", f), "f is NaN"), "NaN should format to \"NaN\"")
+	testr.check(c, std.eq(std.fmt("g is {}", g), "g is NaN"), "NaN should format to \"NaN\"")
+	testr.check(c, std.eq(std.fmt("f2 is {}", f2), "f2 is NaN"), "alt NaN should format to \"NaN\"")
+	testr.check(c, std.eq(std.fmt("g2 is {}", g2), "g2 is NaN"), "alt NaN should format to \"NaN\"")
+}
+
+const putInf = {c
+        var f : flt32 = std.flt32inf()
+        var g : flt64 = std.flt64inf()
+	testr.check(c, std.eq(std.fmt("f is {}", f), "f is Inf"), "Inf should format to \"Inf\"")
+	testr.check(c, std.eq(std.fmt("g is {}", g), "g is Inf"), "Inf should format to \"Inf\"")
+}
+