refactor: Make sum_real ext generic (IFloatingPoint<T>)
Also add bool param 'nan_if_none' (to return NaN instead of 0 when values contains no real numbers)
This commit is contained in:
1 parent
f9d269c750
commit
7cfc53eba8
1 file changed
+52
-6
@@ -101,6 +101,28 @@ namespace bts.utils {
|
||||
this T value, T factor, out int n_factors_removed) where T : IFloatingPoint<T> =>
|
||||
MathUtils.factor_out(value, factor, out n_factors_removed);
|
||||
|
||||
/// <summary>
|
||||
/// Adds <paramref name="b"/> to <paramref name="a"/> if both terms are real.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If only <paramref name="a"/> is real, returns <paramref name="a"/>.
|
||||
/// If only <paramref name="b"/> is real, returns <paramref name="b"/>.
|
||||
/// If neither term is real, returns NaN.
|
||||
/// </remarks>
|
||||
public static T add_real<T>(this T a, T b) where T : IFloatingPoint<T> =>
|
||||
new[] { a, b }.sum_real(true);
|
||||
|
||||
/// <summary>
|
||||
/// Subtracts <paramref name="b"/> from <paramref name="a"/> if both terms are real.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If only <paramref name="a"/> is real, returns <paramref name="a"/>.
|
||||
/// If only <paramref name="b"/> is real, returns -<paramref name="b"/>
|
||||
/// If neither term is real, returns NaN.
|
||||
/// </remarks>
|
||||
public static T subtract_real<T>(this T a, T b) where T : IFloatingPoint<T> =>
|
||||
new[] { a, -b }.sum_real(true);
|
||||
|
||||
/// <summary>
|
||||
/// Returns the smaller of two numbers
|
||||
/// </summary>
|
||||
@@ -149,16 +171,40 @@ namespace bts.utils {
|
||||
MathUtils.safe_divide(lhs, rhs);
|
||||
|
||||
/// <summary>
|
||||
/// Computes the sum of a sequence of <see cref="double"/> values (skips non-real numbers)
|
||||
/// Computes the sum of a sequence of <see cref="T"/> values (skips non-real numbers)
|
||||
/// </summary>
|
||||
public static double sum_real(this IEnumerable<double> values) {
|
||||
double res = 0;
|
||||
foreach (var v in values) {
|
||||
if (MathUtils.is_real(v)) {
|
||||
/// <param name="nan_if_none">
|
||||
/// Whether to return <see cref="T.NaN"/> or <see cref="T.Zero"/> if <paramref name="values"/>
|
||||
/// contains no real numbers
|
||||
/// </param>
|
||||
public static T sum_real<T>(this IEnumerable<T> values, bool nan_if_none = false)
|
||||
where T : IFloatingPoint<T> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user