diff --git a/contrib/btree_gist/btree_interval.c b/contrib/btree_gist/btree_interval.c
index b51b2946367..b44074ed142 100644
--- a/contrib/btree_gist/btree_interval.c
+++ b/contrib/btree_gist/btree_interval.c
@@ -78,13 +78,25 @@ gbt_intvkey_cmp(const void *a, const void *b, FmgrInfo *flinfo)
 static double
 intr2num(const Interval *i)
 {
-	return INTERVAL_TO_SEC(i);
+	if (INTERVAL_IS_NOEND(i))
+		return get_float8_infinity();
+	else if (INTERVAL_IS_NOBEGIN(i))
+		return -get_float8_infinity();
+	else
+		return INTERVAL_TO_SEC(i);
 }
 
 static float8
 gbt_intv_dist(const void *a, const void *b, FmgrInfo *flinfo)
 {
-	return fabs(intr2num((const Interval *) a) - intr2num((const Interval *) b));
+	double		da = intr2num((const Interval *) a);
+	double		db = intr2num((const Interval *) b);
+
+	/* Inf - Inf would yield NaN, but we want to return zero instead */
+	if (da == db)
+		return 0.0;
+	else
+		return fabs(da - db);
 }
 
 /*
@@ -317,7 +329,7 @@ gbt_intv_penalty(PG_FUNCTION_ARGS)
 	inew[0] = intr2num(&newentry->lower);
 	inew[1] = intr2num(&newentry->upper);
 
-	penalty_num(result, iorg[0], iorg[1], inew[0], inew[1]);
+	float_penalty_num(result, iorg[0], iorg[1], inew[0], inew[1]);
 
 	PG_RETURN_POINTER(result);
 }
diff --git a/contrib/btree_gist/btree_utils_num.h b/contrib/btree_gist/btree_utils_num.h
index 52f531f70e4..c427f2bf68d 100644
--- a/contrib/btree_gist/btree_utils_num.h
+++ b/contrib/btree_gist/btree_utils_num.h
@@ -184,6 +184,7 @@ float_penalty_num_impl(double olower, double oupper,
  * Convert an Interval to an approximate equivalent number of seconds
  * (as a double).  Here because we need it for time/timetz as well as
  * interval.  See interval_cmp_internal for comparison.
+ * Caution: don't use this if the interval could be +-Infinity.
  */
 #define INTERVAL_TO_SEC(ivp) \
 	(((double) (ivp)->time) / ((double) USECS_PER_SEC) + \
