From 7cfc53eba86fed3a7b3343278201e90f6f155f7a Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 27 Jul 2022 10:41:20 -0400 Subject: [PATCH] refactor: Make sum_real ext generic (IFloatingPoint) Also add bool param 'nan_if_none' (to return NaN instead of 0 when values contains no real numbers) --- .../spark_api/utils/NumericExtensions.cs | 58 +++++++++++++++++-- 1 file changed, 52 insertions(+), 6 deletions(-) diff --git a/src/client/spark_api/utils/NumericExtensions.cs b/src/client/spark_api/utils/NumericExtensions.cs index 2244fd8e1..20a4dd9bd 100644 --- a/src/client/spark_api/utils/NumericExtensions.cs +++ b/src/client/spark_api/utils/NumericExtensions.cs @@ -101,6 +101,28 @@ namespace bts.utils { this T value, T factor, out int n_factors_removed) where T : IFloatingPoint => MathUtils.factor_out(value, factor, out n_factors_removed); + /// + /// Adds to if both terms are real. + /// + /// + /// If only is real, returns . + /// If only is real, returns . + /// If neither term is real, returns NaN. + /// + public static T add_real(this T a, T b) where T : IFloatingPoint => + new[] { a, b }.sum_real(true); + + /// + /// Subtracts from if both terms are real. + /// + /// + /// If only is real, returns . + /// If only is real, returns - + /// If neither term is real, returns NaN. + /// + public static T subtract_real(this T a, T b) where T : IFloatingPoint => + new[] { a, -b }.sum_real(true); + /// /// Returns the smaller of two numbers /// @@ -149,16 +171,40 @@ namespace bts.utils { MathUtils.safe_divide(lhs, rhs); /// - /// Computes the sum of a sequence of values (skips non-real numbers) + /// Computes the sum of a sequence of values (skips non-real numbers) /// - public static double sum_real(this IEnumerable values) { - double res = 0; - foreach (var v in values) { - if (MathUtils.is_real(v)) { + /// + /// Whether to return or if + /// contains no real numbers + /// + public static T sum_real(this IEnumerable values, bool nan_if_none = false) + where T : IFloatingPoint { + return nan_if_none ? nan_if_none_impl() : normal_impl(); + + T normal_impl() { + T res = T.Zero; + foreach (var v in values) { + if (v.is_real()) { + res += v; + } + } + return res; + } + + T nan_if_none_impl() { + T res = T.NaN; + foreach (var v in values) { + if (!v.is_real()) { + continue; + } + if (res.is_nan()) { + res = v; + continue; + } res += v; } + return res; } - return res; } } }