Extend the math expression parser's combinatorics, statistics, roots, powers, and division past the reals (#4574)

This commit is contained in:
Keavon Chambers authored and GitHub committed 2026-09-22 16:00:08 -07:00
1 parent 69398a6703
commit b610d9bc23
4 files changed
+321 -92

No files matched your search

+140 -81
View File
@@ -1,6 +1,7 @@
use crate::value::{Complex, Number, Value};
use crate::ast::BinaryOp;
use crate::value::{Complex, Number, Value, complex_divide, complex_log_gamma};
use num_complex::ComplexFloat;
use std::f64::consts::LN_2;
use std::f64::consts::{LN_2, PI, TAU};
pub type BuiltinFunction = fn(&[Value]) -> Option<Value>;
@@ -13,10 +14,10 @@ fn integer_operand(value: f64) -> Option<u128> {
(value.is_finite() && value.abs() <= EXACT_INTEGER_LIMIT).then(|| (value as i64).unsigned_abs() as u128)
}
/// Rounds a combinatorics operand to the nearest whole number, or `None` when it is negative, non-finite, or beyond f64's exactly-representable integer range.
fn whole_operand(value: f64) -> Option<u64> {
let value = value.round();
(0. ..=EXACT_INTEGER_LIMIT).contains(&value).then_some(value as u64)
/// Reads a combinatorics count as a whole number from zero up to f64's exactly-representable limit, or `None` for a fractional one rather than rounding it.
fn whole_count(value: &Value) -> Option<u64> {
let value = value.as_real()?;
(value.fract() == 0. && (0. ..=EXACT_INTEGER_LIMIT).contains(&value)).then_some(value as u64)
}
/// Accumulates one multiplicative `step` per iteration, stopping once the running product reaches infinity, since it stays there.
@@ -32,19 +33,25 @@ fn bounded_product(steps: impl Iterator<Item = u64>, step: impl Fn(f64, u64) ->
product
}
/// Collects every argument as a real number, or `None` if any is complex or there are no arguments at all.
fn real_operands(values: &[Value]) -> Option<Vec<f64>> {
/// Every argument as a real number, or `None` if any is complex or there are no arguments at all.
fn real_operands(values: &[Value]) -> Option<impl Iterator<Item = f64> + Clone + '_> {
if values.is_empty() || !values.iter().all(|value| value.as_real().is_some()) {
return None;
}
Some(values.iter().filter_map(Value::as_real))
}
/// Every argument in the complex plane, or `None` if there are no arguments at all.
fn complex_operands(values: &[Value]) -> Option<impl Iterator<Item = Complex> + Clone + '_> {
if values.is_empty() {
return None;
}
Some(values.iter().map(|Value::Number(number)| number.as_complex()))
}
values
.iter()
.map(|value| match value {
Value::Number(Number::Real(real)) => Some(*real),
_ => None,
})
.collect()
/// The [`power_of_two_scale`] of the numbers' largest part.
fn scale_of(numbers: impl Iterator<Item = Complex>) -> f64 {
power_of_two_scale(numbers.flat_map(|number| [number.re, number.im]))
}
/// Applies a one-argument function that may climb into the complex plane: a real result that does not exist,
@@ -67,8 +74,8 @@ fn climbing(values: &[Value], real_function: fn(f64) -> f64, complex_function: f
/// The power of two at or below the largest magnitude, dividing by which is exact and brings every value within ±2, so sums and
/// squares of the scaled values neither overflow nor underflow. It's 1 when the largest magnitude is zero, subnormal, or infinite.
fn power_of_two_scale(reals: &[f64]) -> f64 {
let largest = reals.iter().fold(0_f64, |largest, real| largest.max(real.abs()));
fn power_of_two_scale(reals: impl Iterator<Item = f64>) -> f64 {
let largest = reals.fold(0_f64, |largest, real| largest.max(real.abs()));
if !largest.is_normal() {
return 1.;
}
@@ -77,15 +84,15 @@ fn power_of_two_scale(reals: &[f64]) -> f64 {
f64::from_bits(largest.to_bits() & (0x7FF << 52))
}
/// Computes the variance of the real arguments divided by the returned scale, over the count less `correction` (1 for a sample,
/// undefined for a single value, or 0 for a population). Staying scaled lets a standard deviation take its root before overflowing.
/// Computes the variance of the arguments, the mean of `|x - mean|²`, divided by the returned scale, over the count less `correction`
/// (1 for a sample, undefined for a single value, or 0 for a population). Staying scaled lets a standard deviation take its root before overflowing.
fn scaled_variance(values: &[Value], correction: usize) -> Option<(f64, f64)> {
let reals = real_operands(values)?;
let divisor = reals.len().checked_sub(correction).filter(|divisor| *divisor > 0)? as f64;
let scale = power_of_two_scale(&reals);
let numbers = complex_operands(values)?;
let divisor = values.len().checked_sub(correction).filter(|divisor| *divisor > 0)? as f64;
let scale = scale_of(numbers.clone());
let mean = reals.iter().map(|real| real / scale).sum::<f64>() / reals.len() as f64;
let variance = reals.iter().map(|real| (real / scale - mean).powi(2)).sum::<f64>() / divisor;
let mean = numbers.clone().map(|number| number / scale).sum::<Complex>() / values.len() as f64;
let variance = numbers.map(|number| (number / scale - mean).norm_sqr()).sum::<f64>() / divisor;
Some((variance, scale))
}
@@ -130,6 +137,61 @@ fn checked_lcm(a: u128, b: u128) -> Option<u128> {
(a / gcd(a, b)).checked_mul(b)
}
/// `choose(n, r)` over a whole nonnegative top, exact while it fits, and zero once `r` exceeds `n`.
fn whole_binomial(n: f64, r: u64) -> f64 {
if r as f64 > n {
return 0.;
}
// Multiplying then dividing at each step keeps every intermediate whole, and the smaller of `r` and `n - r` halves the steps
let r = r.min((n - r as f64) as u64);
bounded_product(1..=r, |accumulated, k| accumulated * (n - r as f64 + k as f64) / k as f64)
}
/// `pick(n, r)` over a whole nonnegative top, and zero once `r` exceeds `n`.
fn whole_falling_factorial(n: f64, r: u64) -> f64 {
if r as f64 > n {
return 0.;
}
bounded_product(0..r, |accumulated, k| accumulated * (n - k as f64))
}
/// The falling factorial `x (x - 1) ... (x - r + 1)` over any top, or the binomial coefficient dividing it by `r!`, by direct
/// product (a negative whole top as `(-1)^r` times that of `|x| + r - 1`), or past a few thousand terms of any other top, the gamma function.
fn combinatorial(x: Number, r: u64, binomial: bool) -> Value {
if let Some(real) = x.as_real()
&& (real.fract() == 0. || real.is_infinite())
{
let sign = if real < 0. && r % 2 == 1 { -1. } else { 1. };
let top = if real < 0. { r as f64 - 1. - real } else { real };
let product = if binomial { whole_binomial(top, r) } else { whole_falling_factorial(top, r) };
return Value::from_f64(sign * product);
}
// The direct product keeps small cases exact at a step per count, so only a count past a few thousand takes the gamma function
const DIRECT_PRODUCT_LIMIT: u64 = 4096;
let z = x.as_complex();
let product = (r <= DIRECT_PRODUCT_LIMIT).then(|| {
if binomial {
(1..=r).fold(Complex::from(1.), |accumulated, k| accumulated * (z - (k - 1) as f64) / k as f64)
} else {
(0..r).fold(Complex::from(1.), |accumulated, k| accumulated * (z - k as f64))
}
});
// An overflowed product has NaN cross terms, so the gamma function takes over with the overflow's direction
let result = match product {
Some(product) if !Number::Complex(product).is_nan() => product,
_ => {
let count_log = if binomial { complex_log_gamma(Complex::from(r as f64 + 1.)) } else { Complex::from(0.) };
(complex_log_gamma(z + 1.) - complex_log_gamma(z - r as f64 + 1.) - count_log).exp()
}
};
// A real top has a real answer, so the rounding residue in the imaginary part is dropped
Value::Number(if x.as_real().is_some() { Number::Real(result.re) } else { Number::Complex(result) })
}
/// Resolves a base-suffixed function name like `log2` or `root3.25` into the corresponding two-argument
/// function and the baked-in second argument parsed from the suffix.
pub fn suffixed_function(name: &str) -> Option<(BuiltinFunction, f64)> {
@@ -228,12 +290,14 @@ pub fn builtin_function(name: &str) -> Option<Builtin> {
Some(if root.is_nan() { Value::from(Complex::new(*x, 0.).powf(1. / *n)) } else { Value::from_f64(root) })
}
[Value::Number(Number::Complex(x)), Value::Number(Number::Real(n))] => Some(Value::from(x.powf(1. / *n))),
// A complex degree is the general power `x^(1/n)`
[Value::Number(x), Value::Number(n)] => Some(Value::from(x.as_complex().powc(n.as_complex().inv()))),
_ => None,
}),
// Geometry Functions
// Folding pairwise hypotenuses gives the root of the sum of squares without ever squaring, avoiding overflow
"hypot" => variadic(|values| Some(Value::from_f64(real_operands(values)?.into_iter().fold(0., f64::hypot)))),
"hypot" => variadic(|values| Some(Value::from_f64(real_operands(values)?.fold(0., f64::hypot)))),
"atan2" => fixed_arity(|values| match values {
[Value::Number(Number::Real(y)), Value::Number(Number::Real(x))] => Some(Value::Number(Number::Real(y.atan2(*x)))),
@@ -289,20 +353,24 @@ pub fn builtin_function(name: &str) -> Option<Builtin> {
Some(Value::Number(Number::Real(max)))
}),
// Statistics across one or more real arguments
// Statistics across one or more arguments, with the median and mode over real ones since they need an order
// TODO: Offer `avg` and `average` as autocomplete aliases in the expression widget, resolving to `mean`
"mean" => variadic(|values| {
let reals = real_operands(values)?;
let scale = power_of_two_scale(&reals);
Some(Value::from_f64(reals.iter().map(|real| real / scale).sum::<f64>() / reals.len() as f64 * scale))
let numbers = complex_operands(values)?;
let scale = scale_of(numbers.clone());
Some(Value::from(numbers.map(|number| number / scale).sum::<Complex>() / values.len() as f64 * scale))
}),
"median" => variadic(|values| {
let mut reals = real_operands(values)?;
let mut reals: Vec<f64> = real_operands(values)?.collect();
reals.sort_by(f64::total_cmp);
let middle = reals.len() / 2;
// An even count has no single middle value, so the two straddling it are averaged
let median = if reals.len() % 2 == 0 { reals[middle - 1].midpoint(reals[middle]) } else { reals[middle] };
let median = if reals.len().is_multiple_of(2) {
reals[middle - 1].midpoint(reals[middle])
} else {
reals[middle]
};
Some(Value::from_f64(median))
}),
@@ -313,41 +381,54 @@ pub fn builtin_function(name: &str) -> Option<Builtin> {
"stdev" => variadic(|values| scaled_variance(values, 1).map(|(variance, scale)| Value::from_f64(variance.sqrt() * scale))),
"stdevpop" => variadic(|values| scaled_variance(values, 0).map(|(variance, scale)| Value::from_f64(variance.sqrt() * scale))),
// The principal root of the product, from the mean of the magnitudes' logarithms (so nothing overflows) and the product's
// argument wrapped into `(-π, π]`, so `geomean(-1, -4)` is 2 and `geomean(-1, 2)` climbs to `i√2` like `sqrt(-2)`
"geomean" => variadic(|values| {
let reals = real_operands(values)?;
// A negative operand has no real geometric mean, and averaging the logarithms keeps the product from overflowing
if reals.iter().any(|real| *real < 0.) {
return None;
let numbers = complex_operands(values)?;
// One value is its own mean exactly, where the polar form below would leave a residue on a negative one
if let [value] = values {
return Some(*value);
}
Some(Value::from_f64((reals.iter().map(|real| real.ln()).sum::<f64>() / reals.len() as f64).exp()))
let count = values.len() as f64;
let log_magnitude = numbers.clone().map(|number| number.norm().ln()).sum::<f64>() / count;
let argument = numbers.map(|number| number.arg()).sum::<f64>().rem_euclid(TAU);
let argument = if argument > PI { argument - TAU } else { argument };
Some(Value::from(Complex::new(log_magnitude, argument / count).exp()))
}),
"harmmean" => variadic(|values| {
let reals = real_operands(values)?;
let numbers = complex_operands(values)?;
// Like the geometric mean, a negative operand has no meaningful harmonic mean, while a zero one makes it zero
if reals.iter().any(|real| *real < 0.) {
return None;
// A zero operand makes the mean zero, and only infinite ones make it their own mean, each contributing a zero reciprocal
let smallest = numbers.clone().map(|number| number.norm()).fold(f64::INFINITY, f64::min);
if smallest == 0. {
return Some(Value::from_f64(0.));
}
let smallest = reals.iter().copied().fold(f64::INFINITY, f64::min);
if smallest == 0. || smallest.is_infinite() {
return Some(Value::from_f64(smallest));
if smallest.is_infinite() {
return Some(Value::from(numbers.sum::<Complex>() / values.len() as f64));
}
// Dividing the smallest operand by each keeps every reciprocal term within 1, so their sum can't overflow
let scaled_reciprocal_sum = reals.iter().map(|real| smallest / real).sum::<f64>();
Some(Value::from_f64(reals.len() as f64 / scaled_reciprocal_sum * smallest))
// Dividing the smallest magnitude by each operand keeps every reciprocal term within 1, so their sum can't overflow
let scaled_reciprocal_sum = Number::Complex(numbers.map(|number| complex_divide(Complex::from(smallest), number)).sum::<Complex>()).canonical();
// Reciprocals that cancel, as in `harmmean(-1, 1)`, sum to zero, and the language's own division takes that to infinity
let count = Number::Real(values.len() as f64);
count
.binary_op(BinaryOp::Div, scaled_reciprocal_sum)?
.binary_op(BinaryOp::Mul, Number::Real(smallest))
.map(Value::Number)
}),
"rms" => variadic(|values| {
let reals = real_operands(values)?;
let scale = power_of_two_scale(&reals);
let mean_square = reals.iter().map(|real| (real / scale).powi(2)).sum::<f64>() / reals.len() as f64;
let numbers = complex_operands(values)?;
let scale = scale_of(numbers.clone());
let mean_square = numbers.map(|number| (number / scale).norm_sqr()).sum::<f64>() / values.len() as f64;
Some(Value::from_f64(mean_square.sqrt() * scale))
}),
"mode" => variadic(|values| {
let mut reals = real_operands(values)?;
let mut reals: Vec<f64> = real_operands(values)?.collect();
reals.sort_by(f64::total_cmp);
// In ascending order, the first run of the greatest length is the smallest of the most frequent values, and no mode exists when no value repeats
@@ -428,46 +509,24 @@ pub fn builtin_function(name: &str) -> Option<Builtin> {
}),
"gcd" => variadic(|values| {
let reduced = real_operands(values)?
.into_iter()
.try_fold(0_u128, |accumulated, real| Some(gcd(accumulated, integer_operand(real)?)))?;
let reduced = real_operands(values)?.try_fold(0_u128, |accumulated, real| Some(gcd(accumulated, integer_operand(real)?)))?;
Some(Value::from_f64(reduced as f64))
}),
"lcm" => variadic(|values| {
let reduced = real_operands(values)?
.into_iter()
.try_fold(1_u128, |accumulated, real| checked_lcm(accumulated, integer_operand(real)?))?;
let reduced = real_operands(values)?.try_fold(1_u128, |accumulated, real| checked_lcm(accumulated, integer_operand(real)?))?;
Some(Value::from_f64(reduced as f64))
}),
// Combinatorics over whole numbers: `choose(n, r)` is the binomial coefficient and `pick(n, r)` the falling factorial
"choose" => fixed_arity(|values| match values {
[Value::Number(Number::Real(n)), Value::Number(Number::Real(r))] => {
let (n, r) = (whole_operand(*n)?, whole_operand(*r)?);
if r > n {
return Some(Value::from_f64(0.));
}
// Multiplying then dividing at each step keeps every intermediate whole, and the smaller of `r` and `n - r` halves the steps
let r = r.min(n - r);
let binomial = bounded_product(1..=r, |accumulated, k| accumulated * (n - r + k) as f64 / k as f64);
Some(Value::from_f64(binomial))
}
_ => None,
// Combinatorics over any top and a whole count: `choose(x, r)` is the binomial coefficient and `pick(x, r)` the falling factorial
"choose" => fixed_arity(|values| {
let [Value::Number(x), r] = values else { return None };
Some(combinatorial(*x, whole_count(r)?, true))
}),
"pick" => fixed_arity(|values| match values {
[Value::Number(Number::Real(n)), Value::Number(Number::Real(r))] => {
let (n, r) = (whole_operand(*n)?, whole_operand(*r)?);
if r > n {
return Some(Value::from_f64(0.));
}
let falling_factorial = bounded_product(0..r, |accumulated, k| accumulated * (n - k) as f64);
Some(Value::from_f64(falling_factorial))
}
_ => None,
"pick" => fixed_arity(|values| {
let [Value::Number(x), r] = values else { return None };
Some(combinatorial(*x, whole_count(r)?, false))
}),
// The conjugate negates the imaginary part
+104 -5
View File
@@ -147,6 +147,9 @@ mod tests {
"gcd(inf, 6)",
"gcd(10000000000000000000, 2)",
"mod(5, 0)",
"choose(2.5, 1.5)",
"pick(3, 0.5)",
"choose(3, -1)",
"(-1)!",
"(-2)!",
"(-inf)!",
@@ -178,6 +181,52 @@ mod tests {
}
}
#[test]
fn combinatorics_extend_past_the_whole_numbers() {
// Compared relatively like the factorial: a count up to a few thousand multiplies out directly, and a larger one goes
// through the gamma function, whose logarithms in the tens of thousands cost a couple of digits
for (input, expected, tolerance) in [
("choose(0.5, 200)", Complex::from(-9.992306256589706e-5), 1e-12),
("choose(10.5, 100)", Complex::from(-7.091868840771164e-17), 1e-12),
("choose(-2.5, 7)", Complex::from(-17.80517578125), 1e-12),
("choose(-0.5, 50)", Complex::from(0.07958923738717877), 1e-12),
("pick(-2.5, 7)", Complex::from(-89738.0859375), 1e-12),
("choose(1e22, 2)", Complex::from(5e43), 1e-12),
("choose(1.5 + 2i, 3)", Complex::new(-1.0625, -1.4166666666666667), 1e-12),
("pick(1.5 + 2i, 3)", Complex::new(-6.375, -8.5), 1e-12),
("choose(0.5, 5000)", Complex::from(-7.979444083790532e-7), 1e-10),
("choose(10.5, 8000)", Complex::from(-4.9672984268570704e-39), 1e-10),
("choose(-0.5, 5000)", Complex::from(0.007978646139382154), 1e-10),
("choose(1.5 + 2i, 5000)", Complex::new(-2.541871408941716e-8, -8.84744846043224e-9), 1e-10),
] {
let Value::Number(actual) = evaluate(input).unwrap().unwrap();
let actual = actual.as_complex();
assert!((actual - expected).norm() / expected.norm() < tolerance, "`{input}`: expected {expected}, got {actual}");
}
}
#[test]
fn simple_complex_quotients_are_exact() {
// Smith's algorithm rounds nothing on these, where dividing by the norm twice loses an ulp
for (input, expected) in [
("(1 + i) / (1 - i)", Complex::new(0., 1.)),
("2 / (1 - i)", Complex::new(1., 1.)),
("(3 + 4i) / (1 + 2i)", Complex::new(2.2, -0.4)),
("harmmean(i, 1)", Complex::new(1., 1.)),
] {
assert_eq!(evaluate(input).unwrap().unwrap(), Value::from(expected), "`{input}`");
}
}
#[test]
fn small_combinatorics_are_exact() {
// The direct product leaves no rounding behind on these, where the gamma function would
for (input, expected) in [("choose(2.5, 2)", 1.875), ("pick(2.5, 2)", 3.75), ("choose(-0.5, 2)", 0.375)] {
assert_eq!(evaluate(input).unwrap().unwrap().as_real(), Some(expected), "`{input}`");
}
assert_eq!(evaluate("choose(i, 2)").unwrap().unwrap(), Value::from(Complex::new(-0.5, -0.5)));
}
#[test]
fn host_values_are_admitted_where_read() {
struct Host;
@@ -209,10 +258,8 @@ mod tests {
#[test]
fn statistics_without_an_answer_are_errors() {
// No value repeats, so no mode exists, and negative operands have no geometric or harmonic mean
for input in ["mode(1, 2, 3)", "geomean(-1, 4)", "harmmean(1, -1)"] {
assert!(evaluate(input).unwrap().is_err(), "expected `{input}` to be an evaluation error");
}
// No value repeats, so no mode exists
assert!(evaluate("mode(1, 2, 3)").unwrap().is_err());
// A single value has no spread to estimate a sample from
for input in ["variance(5)", "stdev(5)"] {
@@ -605,6 +652,22 @@ mod tests {
statistics_rms: "rms(3, 4)" => 12.5_f64.sqrt(),
statistics_mode: "mode(2, 3, 3, 1, 2)" => 2.,
statistics_count: "count(1, 2, 3)" => 3.,
statistics_mean_complex: "mean(i, 3i)" => Complex::new(0., 2.),
statistics_mean_lands_real: "mean(1 + i, 3 - i)" => 2.,
statistics_variance_complex: "variance(i, -i)" => 2.,
statistics_stdev_population_complex: "stdevpop(1 + i, 1 - i)" => 1.,
statistics_rms_complex: "rms(3i, 4)" => 12.5_f64.sqrt(),
statistics_geomean_single: "geomean(-3)" => -3.,
statistics_geomean_negative_pair: "geomean(-1, -4)" => 2.,
statistics_geomean_climbs: "geomean(-1, 2)" => Complex::new(0., 2_f64.sqrt()),
statistics_geomean_complex: "geomean(i, 1)" => Complex::new(std::f64::consts::FRAC_1_SQRT_2, std::f64::consts::FRAC_1_SQRT_2),
statistics_harmmean_negative: "harmmean(-1, -3)" => -1.5,
statistics_harmmean_cancelling: "harmmean(-1, 1)" => f64::INFINITY,
statistics_harmmean_complex: "harmmean(i, 1)" => Complex::new(1., 1.),
statistics_geomean_infinite: "geomean(inf, 1)" => f64::INFINITY,
statistics_harmmean_infinite_operand: "harmmean(inf, 1)" => 2.,
statistics_harmmean_all_infinite: "harmmean(-inf, -inf)" => f64::NEG_INFINITY,
statistics_harmmean_huge: "harmmean(1e308, 1e308)" => 1e308,
logical_xor_odd_parity: "xor(1, 1, 1)" => 1.,
logical_xor_even_parity: "xor(1, 0, 1)" => 0.,
mapping_remap: "remap(5, 0, 10, 0, 100)" => 50.,
@@ -615,15 +678,28 @@ mod tests {
gcd_negative_operand: "gcd(-24, 18)" => 6.,
lcm_negative_operand: "lcm(-4, 6)" => 12.,
// Combinatorics over whole numbers
// Combinatorics over any top and a whole count
combinatorics_choose: "choose(5, 2)" => 10.,
combinatorics_choose_symmetric: "choose(30, 28)" => 435.,
combinatorics_choose_beyond_n: "choose(3, 5)" => 0.,
combinatorics_choose_fractional_top: "choose(2.4, 1)" => 2.4,
combinatorics_choose_half: "choose(0.5, 2)" => -0.125,
combinatorics_choose_negative_top: "choose(-1, 3)" => -1.,
combinatorics_choose_negative_top_larger: "choose(-5, 3)" => -35.,
combinatorics_choose_zero_count: "choose(2.5, 0)" => 1.,
combinatorics_choose_complex_top: "choose(i, 2)" => Complex::new(-0.5, -0.5),
combinatorics_pick: "pick(5, 2)" => 20.,
combinatorics_pick_all: "pick(4, 4)" => 24.,
combinatorics_pick_fractional_top: "pick(2.5, 2)" => 3.75,
combinatorics_pick_negative_top: "pick(-5, 3)" => -210.,
combinatorics_pick_complex_top: "pick(i, 2)" => Complex::new(-1., -1.),
// A result beyond f64 stops at infinity instead of stepping through quadrillions of terms
combinatorics_choose_overflows: "choose(9007199254740992, 4503599627370496)" => f64::INFINITY,
combinatorics_pick_overflows: "pick(9007199254740992, 9007199254740992)" => f64::INFINITY,
combinatorics_pick_fractional_overflows: "pick(0.5, 200)" => f64::NEG_INFINITY,
combinatorics_pick_complex_overflows: "|pick(1.5 + 2i, 300)|" => f64::INFINITY,
combinatorics_choose_infinite_top: "choose(inf, 2)" => f64::INFINITY,
combinatorics_pick_negative_infinite_top: "pick(-inf, 3)" => f64::NEG_INFINITY,
// Truth values are the numbers 1 and 0
constant_truth_values: "true + true - false" => 2.,
@@ -669,6 +745,8 @@ mod tests {
root_negative_odd: "root(-8, 3)" => -2.,
root_negative_odd_reciprocal: "root(-8, -3)" => -0.5,
root_negative_even: "root(-4, 2)" => Complex::new(0., 2.),
root_complex_degree: "root(8, 3i)" => Complex::new(0.7692389013639721, -0.6389612763136348),
root_complex_degree_lands_real: "root(i, i)" => std::f64::consts::FRAC_PI_2.exp(),
// Equality spans real and complex operands
mixed_equality: "1 == i" => 0.,
@@ -682,6 +760,27 @@ mod tests {
value_identity_signed_zero: "1/(-0)" => f64::INFINITY,
value_identity_ceiling: "1/ceil(-0.5)" => f64::INFINITY,
// Division by zero heads to infinity part by part with each part's own sign, like an overflow, rather than turning indeterminate
division_by_zero_imaginary: "i / 0" => Complex::new(0., f64::INFINITY),
division_by_zero_complex: "(1 + i) / 0" => Complex::new(f64::INFINITY, f64::INFINITY),
division_by_zero_complex_signs: "(1 - i) / 0" => Complex::new(f64::INFINITY, f64::NEG_INFINITY),
division_scaled_tiny: "(1e-200i) / (1e-200i)" => 1.,
division_scaled_huge: "(1e200 + 1e200i) / (1e200 + 1e200i)" => 1.,
division_scaled_max: "(1e308 + 1e308i) / (1e308 + 1e308i)" => 1.,
division_scaled_max_dividend: "(1e308 + 1e308i) / (1 + i)" => 1e308,
division_scaled_max_dividend_signs: "(1e308 - 1e308i) / (1 + i)" => Complex::new(0., -1e308),
// A whole exponent on a complex base multiplies out exactly
power_imaginary_square: "i^2" => -1.,
power_imaginary_cube: "i^3" => Complex::new(0., -1.),
power_imaginary_zero: "i^0" => 1.,
power_imaginary_huge: "i^(2^70)" => 1.,
power_complex_square: "(3 + 4i)^2" => Complex::new(-7., 24.),
power_complex_negative: "(1 + i)^-2" => Complex::new(0., -0.5),
power_complex_negative_tiny: "(1e-200i)^-1" => Complex::new(0., -1e200),
power_complex_negative_underflow: "|(1e-200i)^-2|" => f64::INFINITY,
power_complex_overflow: "|(1.5 + 2i)^1000|" => f64::INFINITY,
// Domain climbs: a real input whose answer is complex resolves into the `1, i` plane
climb_sqrt: "sqrt(-4)" => Complex::new(0., 2.),
climb_ln: "ln(-1)" => Complex::new(0., std::f64::consts::PI),
+3 -1
View File
@@ -97,7 +97,9 @@ impl Reducer {
Reducer::Function(function) => {
let values: Vec<Value> = items.iter().map(|&item| Value::from_f64(item)).collect();
function(&values)?.as_real()
// Canonical like a settled result, so a mean that lands on the real line reads as real
let Value::Number(result) = function(&values)?;
result.canonical().as_real()
}
}
}
+74 -5
View File
@@ -1,5 +1,6 @@
use crate::ast::{BinaryOp, UnaryOp};
use std::f64::consts::PI;
use std::ops::Mul;
pub type Complex = num_complex::Complex<f64>;
@@ -186,7 +187,8 @@ impl Number {
BinaryOp::Add => lhs + rhs,
BinaryOp::Sub => lhs - rhs,
BinaryOp::Mul => lhs * rhs,
BinaryOp::Div => lhs / rhs,
BinaryOp::Div => complex_divide(lhs, rhs),
BinaryOp::Pow if rhs.im == 0. => return complex_real_power(lhs, rhs.re),
BinaryOp::Pow => lhs.powc(rhs),
BinaryOp::Leq | BinaryOp::Lt | BinaryOp::Geq | BinaryOp::Gt => {
return None;
@@ -202,7 +204,7 @@ impl Number {
BinaryOp::Add => lhs_complex + rhs,
BinaryOp::Sub => lhs_complex - rhs,
BinaryOp::Mul => lhs_complex * rhs,
BinaryOp::Div => lhs_complex / rhs,
BinaryOp::Div => complex_divide(lhs_complex, rhs),
BinaryOp::Pow => lhs_complex.powc(rhs),
_ => return None,
};
@@ -215,8 +217,9 @@ impl Number {
BinaryOp::Add => lhs + rhs_complex,
BinaryOp::Sub => lhs - rhs_complex,
BinaryOp::Mul => lhs * rhs_complex,
BinaryOp::Div => lhs / rhs_complex,
BinaryOp::Pow => lhs.powf(rhs),
BinaryOp::Div if rhs == 0. => complex_over_zero(lhs, rhs),
BinaryOp::Div => lhs / rhs,
BinaryOp::Pow => return complex_real_power(lhs, rhs),
_ => return None,
};
Some(Number::Complex(result))
@@ -248,6 +251,72 @@ impl Number {
}
}
/// Division by a real zero, sending each nonzero part to the infinity of its own sign as an overflow would, so `i / 0` is `∞i`.
fn complex_over_zero(dividend: Complex, zero: f64) -> Complex {
let part_over_zero = |part: f64| if part == 0. { 0. } else { part / zero };
Complex::new(part_over_zero(dividend.re), part_over_zero(dividend.im))
}
/// Complex division by Smith's algorithm, scaling by the divisor's larger part so neither `|divisor|²` nor the quotient
/// overflows or underflows while the answer fits, and a simple quotient like `(1 + i) / (1 - i)` stays exact.
pub(crate) fn complex_divide(dividend: Complex, divisor: Complex) -> Complex {
// Every part is halved when one passes half of f64::MAX, keeping the quotient while the sums below stay in range
let largest_part = [dividend.re, dividend.im, divisor.re, divisor.im].into_iter().map(f64::abs).fold(0., f64::max);
let (dividend, divisor) = if largest_part > f64::MAX / 2. { (dividend / 2., divisor / 2.) } else { (dividend, divisor) };
let Complex { re: a, im: b } = dividend;
let Complex { re: c, im: d } = divisor;
if c.abs() >= d.abs() {
let ratio = d / c;
let denominator = c + d * ratio;
Complex::new((a + b * ratio) / denominator, (b - a * ratio) / denominator)
} else {
let ratio = c / d;
let denominator = d + c * ratio;
Complex::new((a * ratio + b) / denominator, (b * ratio - a) / denominator)
}
}
/// A complex base under a real exponent: a whole exponent multiplies out exactly by squaring, so `i^2` is `-1` where the polar
/// form leaves a `sin(π)` residue, and any other exponent takes the polar form.
fn complex_real_power(base: Complex, exponent: f64) -> Option<Number> {
if exponent.fract() != 0. || exponent.abs() >= u128::MAX as f64 {
return Some(Number::Complex(base.powf(exponent)));
}
let power = match exponent.abs() as u128 {
0 => Complex::from(1.),
count => whole_power(base, count),
};
// An overflowed product has NaN cross terms, so the polar form takes over with the overflow's direction
if Number::Complex(power).is_nan() {
return Some(Number::Complex(base.powf(exponent)));
}
if exponent < 0. {
return Number::Real(1.).binary_op(BinaryOp::Div, Number::Complex(power).canonical());
}
Some(Number::Complex(power))
}
/// `base^n` for a whole `n` of at least 1 by repeated squaring, in O(log n) multiplications.
fn whole_power<T: Copy + Mul<Output = T>>(mut base: T, mut exponent: u128) -> T {
while exponent & 1 == 0 {
base = base * base;
exponent >>= 1;
}
let mut result = base;
while exponent > 1 {
exponent >>= 1;
base = base * base;
if exponent & 1 == 1 {
result = result * base;
}
}
result
}
/// The factorial of a real number: the exact product for a whole number, and `x! = Γ(x + 1)` past the whole numbers, or
/// `None` at the negative integers (the gamma function's poles, where no signed limit exists) and at -∞.
fn real_factorial(x: f64) -> Option<f64> {
@@ -298,7 +367,7 @@ fn complex_gamma(z: Complex) -> Complex {
}
/// The natural logarithm of the gamma function over the complex plane, by the same approximation and reflection as [`real_gamma`].
fn complex_log_gamma(z: Complex) -> Complex {
pub(crate) fn complex_log_gamma(z: Complex) -> Complex {
if z.re < 0.5 {
// Shifting the real part into `[0, 1)` keeps the sine exact, with a half turn (a sign) for each odd shift
let shift = z.re.floor();