git: 29667c6fcc36 - stable/13 - ping: Avoid reporting NaNs

From: Mark Johnston <markj_at_FreeBSD.org>
Date: Mon, 13 Nov 2023 15:21:14 UTC
The branch stable/13 has been updated by markj:

URL: https://cgit.FreeBSD.org/src/commit/?id=29667c6fcc36de5cf28942bd72e5b5f5926d19f5

commit 29667c6fcc36de5cf28942bd72e5b5f5926d19f5
Author:     Jose Luis Duran <jlduran@gmail.com>
AuthorDate: 2023-10-06 17:55:06 +0000
Commit:     Mark Johnston <markj@FreeBSD.org>
CommitDate: 2023-11-13 15:20:50 +0000

    ping: Avoid reporting NaNs
    
    Avoid calculating the square root of negative zero, which can easily
    happen on certain architectures when calculating the population standard
    deviation with a sample size of one, e.g., 0.01 - (0.1 * 0.1) =
    -0.000000.
    
    Avoid returning a NaN by capping the minimum possible variance value to
    zero (positive).
    
    In the future, maybe skip reporting statistics at all for a single
    sample.
    
    Reported by:    Jenkins
    Reviewed by:    asomers
    MFC after:      1 week
    Pull Request:   https://github.com/freebsd/freebsd-src/pull/863
    Differential Revision:  https://reviews.freebsd.org/D42114
    
    (cherry picked from commit 4d348e83b738347f6aaf2b110459a01c5402d04e)
---
 sbin/ping/ping.c  | 4 ++--
 sbin/ping/ping6.c | 4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/sbin/ping/ping.c b/sbin/ping/ping.c
index f248a0eb738c..e121ebdb19e2 100644
--- a/sbin/ping/ping.c
+++ b/sbin/ping/ping.c
@@ -1521,10 +1521,10 @@ finish(void)
 	if (nreceived && timing) {
 		double n = nreceived + nrepeats;
 		double avg = tsum / n;
-		double vari = tsumsq / n - avg * avg;
+		double stddev = sqrt(fmax(0, tsumsq / n - avg * avg));
 		(void)printf(
 		    "round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n",
-		    tmin, avg, tmax, sqrt(vari));
+		    tmin, avg, tmax, stddev);
 	}
 
 	if (nreceived)
diff --git a/sbin/ping/ping6.c b/sbin/ping/ping6.c
index 432a59bf1303..0edeb01b2dc0 100644
--- a/sbin/ping/ping6.c
+++ b/sbin/ping/ping6.c
@@ -2349,10 +2349,10 @@ summary(void)
 		/* Only display average to microseconds */
 		double num = nreceived + nrepeats;
 		double avg = tsum / num;
-		double dev = sqrt(tsumsq / num - avg * avg);
+		double stddev = sqrt(fmax(0, tsumsq / num - avg * avg));
 		(void)printf(
 		    "round-trip min/avg/max/std-dev = %.3f/%.3f/%.3f/%.3f ms\n",
-		    tmin, avg, tmax, dev);
+		    tmin, avg, tmax, stddev);
 		(void)fflush(stdout);
 	}
 	(void)fflush(stdout);