git: 4d348e83b738 - main - ping: Avoid reporting NaNs

From: Mark Johnston <markj_at_FreeBSD.org>
Date: Wed, 11 Oct 2023 18:01:02 UTC
The branch main has been updated by markj:

URL: https://cgit.FreeBSD.org/src/commit/?id=4d348e83b738347f6aaf2b110459a01c5402d04e

commit 4d348e83b738347f6aaf2b110459a01c5402d04e
Author:     Jose Luis Duran <jlduran@gmail.com>
AuthorDate: 2023-10-06 17:55:06 +0000
Commit:     Mark Johnston <markj@FreeBSD.org>
CommitDate: 2023-10-11 17:48:27 +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
---
 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 072d4607f745..f67d85f30a5d 100644
--- a/sbin/ping/ping.c
+++ b/sbin/ping/ping.c
@@ -1522,10 +1522,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 bd1658f9500a..d14da9c67a52 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);