From 8d90b1ea038005bc4bf55c89df4154a16b87e785 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Thu, 15 Oct 2026 00:07:34 -0500 Subject: [PATCH 1/8] fix(functions): XIRR and IRR follow Excel's solvers XIRR returned the exact root (Newton with fallbacks and a bracketing search), so it differed from Excel at about 1e-8 and converged where Excel gives #NUM!. It now follows Excel's solver as reconstructed by observing Excel with synthetic inputs: a sign-only search that brackets the root from the guess (doubling; bisecting towards 0, halving towards 0 or stepping halfway to -100% when the root is lower), then bisection with the midpoint taken from the upper end, stopping when half the bracket is under 1e-8 * (|rate| + 0.5) and |XNPV| is under 2e-8 * |first value|, at most 100 XNPV evaluations. Dates before the first are allowed as in Excel; a guess at or below -1 is #NUM!. Answers match Excel bit for bit in 888 of 910 synthetic cases with an answer; 97.7% agreement on 1,283 cases. IRR now uses Newton on the discount factor 1/(1+rate), at most 100 steps, stopping at a step under 1e-8, which agrees with Excel's #NUM! cases far better (IRR of -100, 19 zeros, 1E-5 is #NUM!) and with its values to about 1e-12. A guess at or below -1 is #VALUE! like Excel. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 +- crates/functions/src/financial.rs | 275 ++++++++++++++++++++++++++++-- docs/function-parity.md | 15 +- 3 files changed, 274 insertions(+), 20 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07e..4cbf9e65a1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (rows auto-fit oversized fonts on open and whole-row/column formatting) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-15 · **Change:** trivial (progress log: XIRR and IRR follow Excel's solvers) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-15 | XIRR matches Excel's solver bit for bit on ordinary flows (its bisection answer, about 1e-8 from the exact root, instead of the exact root) and its `#NUM!` cases; IRR uses Newton on the discount factor like Excel (`#NUM!` where Excel gives up) | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | | 2026-10-12 | Number formats: a fraction denominator with 65,536 zeros no longer crashes; format codes are capped at 255 characters like Excel (longer codes display as General, `TEXT` gives `#VALUE!`) (#807) | @@ -193,6 +194,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-10-15 | trivial | Progress log: XIRR and IRR follow Excel's solvers | | 2026-10-12 | minor | Rows auto-fit oversized fonts on open and whole-row/column formatting (#833); progress log row | | 2026-10-12 | minor | Progress log: multi-area row/column delete (#758) | | 2026-10-12 | trivial | Progress log: XLSX chart sheets kept on save (#727) | diff --git a/crates/functions/src/financial.rs b/crates/functions/src/financial.rs index 2758246ceb..5807d02c5d 100644 --- a/crates/functions/src/financial.rs +++ b/crates/functions/src/financial.rs @@ -236,8 +236,9 @@ fn npv(a: &[Arg], _c: &mut dyn Ctx) -> R { num_val(sum) } -/// Values and dates for XNPV/XIRR: both must be numeric and of equal length. -fn dated_flows(values: &Value, dates: &Value) -> R<(Vec, Vec)> { +/// Values and dates for XNPV/XIRR: both must be numeric and of equal length. XNPV rejects a +/// date before the first; XIRR (`before_first`) takes it, as Excel does. +fn dated_flows(values: &Value, dates: &Value, before_first: bool) -> R<(Vec, Vec)> { let va = as_array(values); let da = as_array(dates); if va.data.len() != da.data.len() { @@ -259,7 +260,7 @@ fn dated_flows(values: &Value, dates: &Value) -> R<(Vec, Vec)> { } } let d0 = *d.first().ok_or(CellError::Num)?; - if d.iter().any(|&x| x < d0 || x < 0.0) { + if d.iter().any(|&x| (x < d0 && !before_first) || x < 0.0) { return Err(CellError::Num); } Ok((v, d)) @@ -275,35 +276,199 @@ fn xnpv(a: &[Arg], _c: &mut dyn Ctx) -> R { if rate <= -1.0 { return Err(CellError::Num); } - let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value)?; + let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value, false)?; num_val(xnpv_calc(rate, &v, &d)) } +/// Excel's XIRR solver, reconstructed by observing Excel with synthetic inputs (not from its +/// code; its documentation says only "iteration", 100 tries and 0.000001 percent). It looks +/// only at the sign of XNPV until the end, so its answer is the root to about 1e-8, not to the +/// last digit: +/// +/// - Bracket the root from the guess (0 counts as 1e-5): double the rate while XNPV keeps the +/// sign it has at the guess and that sign differs from the first value (the root is higher). +/// Otherwise the root is lower: bisect towards 0 if XNPV changes sign there; halve the rate +/// towards 0 if XNPV is larger in size at 0 than at the guess; otherwise try minus the guess +/// and then step halfway to -100% each time. A negative guess only moves towards 0 (root +/// higher) or towards -100% (root lower). +/// - Bisect the bracket, taking the midpoint from the upper end, until half the bracket is +/// under 1e-8 * (|rate| + 0.5) and |XNPV| is under 2e-8 * |first value|; return that +/// midpoint. A zero XNPV counts as the upper side. +/// - Halving towards 0 that gets within that tolerance of 0 without a sign change goes on with +/// the negative side; at most 100 XNPV evaluations in all; a rate of -100% or an XNPV that +/// can't be computed (a negative base for fractional years) is #NUM!. +struct XirrSolver<'a> { + values: &'a [f64], + years: Vec, + evals: usize, + /// XNPV must be within this of 0 at the answer. + residual: f64, +} + +impl XirrSolver<'_> { + const MAX_EVALS: usize = 100; + + fn tol(rate: f64) -> f64 { + 1e-8 * (rate.abs() + 0.5) + } + + fn same_sign(a: f64, b: f64) -> bool { + a * b > 0.0 + } + + fn f(&mut self, rate: f64) -> R { + self.evals += 1; + if self.evals > Self::MAX_EVALS { + return Err(CellError::Num); + } + let base = 1.0 + rate; + if base == 0.0 { + return Err(CellError::Num); + } + let mut sum = 0.0; + for (x, t) in self.values.iter().zip(&self.years) { + sum += x / base.powf(*t); + } + if sum.is_finite() { Ok(sum) } else { Err(CellError::Num) } + } + + fn solve(&mut self, guess: f64) -> R { + let first = self.values.first().copied().unwrap_or(0.0); + let g = if guess == 0.0 { 1e-5 } else { guess }; + let fg = self.f(g)?; + let higher = fg * first < 0.0; + if g > 0.0 { + if higher { + return self.double(g, fg); + } + let f0 = self.f(0.0)?; + if !Self::same_sign(f0, fg) { + return self.bisect(g, fg, 0.0, f0); + } + if f0.abs() > fg.abs() { + return self.halve(g, fg, g, fg); + } + return self.negative_side(g, fg); + } + if higher { self.halve(g, fg, g, fg) } else { self.towards_minus_one(g, fg) } + } + + fn double(&mut self, mut x: f64, mut fx: f64) -> R { + loop { + let next = 2.0 * x; + let fnext = self.f(next)?; + if !Self::same_sign(fnext, fx) { + return self.bisect(x, fx, next, fnext); + } + (x, fx) = (next, fnext); + } + } + + fn halve(&mut self, mut x: f64, mut fx: f64, g: f64, fg: f64) -> R { + loop { + let step = -x / 2.0; + let next = x + step; + let fnext = self.f(next)?; + if !Self::same_sign(fnext, fx) { + return self.bisect(x, fx, next, fnext); + } + if step.abs() < Self::tol(next) { + if next < 0.0 { + return Err(CellError::Num); + } + return self.negative_side(g, fg); + } + (x, fx) = (next, fnext); + } + } + + fn negative_side(&mut self, g: f64, fg: f64) -> R { + let fm = self.f(-g)?; + if !Self::same_sign(fm, fg) { + return self.bisect(g, fg, -g, fm); + } + self.towards_minus_one(-g, fm) + } + + fn towards_minus_one(&mut self, mut x: f64, mut fx: f64) -> R { + loop { + let next = x + (-1.0 - x) / 2.0; + let fnext = self.f(next)?; + if !Self::same_sign(fnext, fx) { + return self.bisect(x, fx, next, fnext); + } + (x, fx) = (next, fnext); + } + } + + fn bisect(&mut self, a: f64, fa: f64, b: f64, fb: f64) -> R { + let (mut lo, mut flo, mut hi) = if a < b { (a, fa, b) } else { (b, fb, a) }; + loop { + let mid = hi - (hi - lo) / 2.0; + let fm = self.f(mid)?; + if (hi - lo) / 2.0 < Self::tol(mid) && fm.abs() < self.residual { + return Ok(mid); + } + if Self::same_sign(fm, flo) { + (lo, flo) = (mid, fm); + } else { + hi = mid; + } + } + } +} + fn xirr(a: &[Arg], _c: &mut dyn Ctx) -> R { - let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value)?; + let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value, true)?; let guess = opt_num(a, 2, 0.1)?; - if !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) { + if guess <= -1.0 || !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) { return Err(CellError::Num); } - num_val(solve_rate(|r| xnpv_calc(r, &v, &d), guess)?) + let d0 = d.first().copied().unwrap_or(0.0); + let first = v.first().copied().unwrap_or(0.0); + let mut solver = XirrSolver { values: &v, years: d.iter().map(|t| (t - d0) / 365.0).collect(), evals: 0, residual: 2e-8 * first.abs() }; + num_val(solver.solve(guess)?) +} + +/// Excel's IRR solver, approximated from observation (Excel's documentation says 20 tries and +/// 0.00001 percent): Newton's method on the discount factor 1/(1+rate), where the cash flows +/// are a polynomial, from 1/(1+guess) until a step moves less than 1e-8, for at most 100 steps. +/// Excel's answers agree with it to about 1e-12 on ordinary flows (the last digits differ) and +/// on which flows have no answer, apart from a few far from any guess. +fn irr_solve(v: &[f64], guess: f64) -> R { + let mut x = 1.0 / (1.0 + guess); + for _ in 0..100 { + let (mut s, mut ds) = (0.0, 0.0); + for c in v.iter().rev() { + ds = ds * x + s; + s = s * x + c; + } + if ds == 0.0 { + return Err(CellError::Num); + } + let next = x - s / ds; + if !next.is_finite() { + return Err(CellError::Num); + } + if (next - x).abs() < 1e-8 { + return if next > 0.0 { Ok(1.0 / next - 1.0) } else { Err(CellError::Num) }; + } + x = next; + } + Err(CellError::Num) } fn irr(a: &[Arg], _c: &mut dyn Ctx) -> R { let v = array_numbers(&a.first().ok_or(CellError::Value)?.value)?; let guess = opt_num(a, 1, 0.1)?; + // Excel: a guess at or below -100% is #VALUE! for IRR (#NUM! for XIRR). + if guess <= -1.0 { + return Err(CellError::Value); + } if !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) { return Err(CellError::Num); } - let f = |r: f64| { - let mut s = 0.0; - let mut d = 1.0; - for x in &v { - s += x / d; - d *= 1.0 + r; - } - s - }; - num_val(solve_rate(f, guess)?) + num_val(irr_solve(&v, guess)?) } fn mirr(a: &[Arg], _c: &mut dyn Ctx) -> R { @@ -1795,6 +1960,82 @@ mod tests { is_err(ev("CUMIPMT", vec![n(0.01), n(360.0), n(125000.0), n(1.0), n(1.0), n(2.0)]), CellError::Num); } + /// XIRR of `values` on `dates`, with an optional guess, as a number or an error. + fn xirr_of(values: &[f64], dates: &[f64], guess: Option) -> Value { + let mut args = vec![rf(col(values)), rf(col(dates))]; + args.extend(guess.map(n)); + ev("XIRR", args) + } + + #[track_caller] + fn xirr_is(values: &[f64], dates: &[f64], guess: Option, expected: f64) { + assert_eq!(xirr_of(values, dates, guess), Value::Number(expected), "XIRR{values:?} {dates:?} {guess:?}"); + } + + fn irr_of(values: &[f64], guess: Option) -> Value { + let mut args = vec![rf(col(values))]; + args.extend(guess.map(n)); + ev("IRR", args) + } + + /// Expected values observed in Excel 365 with these synthetic inputs. XIRR matches bit for + /// bit: its answer is a bisection midpoint, about 1e-8 from the exact root. + #[test] + fn xirr_follows_excel_bisection() { + let (b, y1, y2) = (43831.0, 44196.0, 44561.0); + // Root 10%: the bracket and so the answer depend on the guess, not on the flows. + xirr_is(&[-100.0, 110.0], &[b, y1], None, 0.099_999_994_039_535_52); + xirr_is(&[-100.0, 121.0], &[b, y2], None, 0.099_999_994_039_535_52); + xirr_is(&[-100.0, 110.0], &[b, y1], Some(0.0), 0.099_999_995_117_187_5); + xirr_is(&[-100.0, 110.0], &[b, y1], Some(0.25), 0.099_999_997_764_825_82); + xirr_is(&[-100.0, 110.0], &[b, y1], Some(5.0), 0.100_000_002_421_438_7); + xirr_is(&[-100.0, 60.0, 60.0], &[b, y1, y2], None, 0.130_662_387_609_481_82); + xirr_is(&[-100.0, 150.0], &[b, y1], None, 0.499_999_994_039_535_54); + // Fractional dates are truncated. + xirr_is(&[-100.0, 60.0, 60.0], &[b, y1 + 0.9, y2 + 0.2], None, 0.130_662_387_609_481_82); + // Negative roots: minus the guess, then halfway to -100% each step. + xirr_is(&[-100.0, 73.0], &[b, y1], None, -0.269_999_996_572_733); + xirr_is(&[-100.0, 13.0], &[b, y1], None, -0.870_000_001_043_081_1); + xirr_is(&[-100.0, 1e-29], &[b, 45658.0], None, -0.999_999_359_104_708); + // A guess of 100% or more steps through rates below -100% (whole years only). + xirr_is(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(2.0), -1.653_112_880_885_601); + xirr_is(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(-0.3), -0.846_887_112_781_405_5); + is_err(xirr_of(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(1.0)), CellError::Num); + // One-day spans. + xirr_is(&[-100.0, 100.01], &[b, b + 1.0], None, 0.037_172_409_892_082_23); + xirr_is(&[-100.0, 99.99], &[b, b + 1.0], None, -0.035_843_667_387_962_34); + xirr_is(&[-100.0, 110.0], &[b, b + 1.0], None, 1_283_305_579_426_611.5); + // Dates before the first are allowed (time runs from the first date); in the second + // case the search finds no sign change. + xirr_is(&[-2416.93, 447.77, 1743.6], &[44331.0, 44498.0, 43849.0], None, -0.974_587_937_071_919_6); + is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, b - 365.0, y2], None), CellError::Num); + // A negative guess never reaches a positive root; a guess at or below -1 is #NUM!. + is_err(xirr_of(&[-100.0, 110.0], &[b, y1], Some(-0.1)), CellError::Num); + is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, y1, y2], Some(-1.0)), CellError::Num); + // Two roots with the guess outside them; all dates the same. + is_err(xirr_of(&[-100.0, 300.0, -210.0], &[b, y1, y2], None), CellError::Num); + is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, b, b], None), CellError::Num); + } + + /// IRR follows Excel's answers to about 1e-12 and its #NUM! cases. + #[test] + fn irr_follows_excel() { + assert_eq!(irr_of(&[-100.0, 110.0], None), Value::Number(0.100_000_000_000_000_09)); + close_tol(irr_of(&[-0.0001, 0.0, 0.0, 0.0, 100.0], None), 30.622_776_600_497_09, 1e-9); + let mut late = vec![-100.0]; + late.extend([0.0; 19]); + late.push(1e-5); + is_err(irr_of(&late, None), CellError::Num); + // ...but from a guess just above -100% Newton creeps down to the root. + let mut late18 = vec![-100.0]; + late18.extend([0.0; 18]); + late18.push(1e-5); + close_tol(irr_of(&late18, Some(-0.99)), -0.571_866_760_128_087_4, 1e-9); + close_tol(irr_of(&[-100.0, 300.0, -210.0], Some(0.9)), 0.887_298_334_620_741_5, 1e-12); + is_err(irr_of(&[-100.0, 60.0, 60.0], Some(-1.0)), CellError::Value); + close_tol(irr_of(&[-100.0, 60.0, 60.0], Some(-0.999_999)), 0.130_662_386_291_807_5, 1e-12); + } + #[test] fn cash_flows() { close_tol(ev("NPV", vec![n(0.1), n(-10000.0), n(3000.0), n(4200.0), n(6800.0)]), 1188.443412, 1e-9); diff --git a/docs/function-parity.md b/docs/function-parity.md index 760ffd6ac3..8f43325b80 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -1,6 +1,6 @@ # Function parity: worksheet functions and formulas -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (USDOLLAR added as a compatibility function; MIRR, COUNTIF and INDIRECT edge cases match Excel 365) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-15 · **Change:** minor (XIRR follows Excel's bisection bit for bit; IRR uses Newton on the discount factor like Excel) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's worksheet functions, category by category, against GridCraft's function library. Part of [target-app-parity.md](target-app-parity.md); gaps feed [gaps.md](gaps.md). @@ -92,7 +92,17 @@ assertions each, but there is no conformance suite against Excel-computed result reports keep finding edge cases: MIN() with no arguments (#138), COUNTBLANK past the used range (#137), ROUND at 15 digits and DATE(1900,2,29) (fixed 10-09), SUMIF sum-range sizing (fixed 10-09). Statistical distributions and financial functions with iterative solvers (RATE, IRR, -XIRR, YIELD) are the highest-risk for last-digit differences. +YIELD) are the highest-risk for last-digit differences. XIRR follows Excel's own solver, +reconstructed from observation: a sign-only search that brackets the root from the guess +(doubling, halving towards 0, or stepping halfway to -100%) and bisects until half the bracket is +under 1e-8 x (|rate| + 0.5) and XNPV is under 2e-8 x the first value, so its answer is the same +midpoint as Excel's, about 1e-8 from the exact root, bit for bit in 888 of 910 synthetic cases +with an answer (97.7% agreement on 1,283 cases including `#NUM!`). Known differences: flows with +several sign changes where Excel returns about 3e-9 (a halving that reached 0), or `#NUM!` for +two roots close to the guess. IRR uses Newton on the discount factor 1/(1+rate), at most 100 steps, +stopping at a step under 1e-8; Excel's last digits differ by about 1e-12 (its exact iteration is +not reconstructed) and a few far-from-guess cases differ in `#NUM!` (93.5% agreement on 708 +cases, from 88%). TEXT() and cell display share `crates/numfmt`; checked against Excel-cached results in number- and text-format test workbooks (352 TEXT cells), all match: @@ -108,6 +118,7 @@ workbooks; results checked in as data, not Excel files) and fixing what it finds | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | XIRR follows Excel's bisection (answers bit for bit, about 1e-8 from the exact root; dates before the first allowed; guess <= -1 is `#NUM!`); IRR uses Newton on the discount factor (`IRR` of -100, 19 zeros, 1E-5 is `#NUM!` like Excel; guess <= -1 is `#VALUE!`) | | 2026-10-12 | minor | USDOLLAR added as a Compatibility function (not on Microsoft's list, so the counts don't change); MIRR with no positive flow is -1, COUNTIF's bare `"<="` / `">="` skip empty strings, INDIRECT with `a1` = FALSE gives `#REF!` for A1-style text (#738) | | 2026-10-11 | minor | TEXT / number formats fixed against Excel-cached results: fraction literals and zero fractions, `0` denominators zero padded, `?` pads the thousands separator, booleans use the text section (226 mismatches → 0 in 352 TEXT cells) | | 2026-10-11 | minor | Iterative calculation: circular references iterate up to Maximum Iterations / Maximum Change when enabled | From c0ae95f721f9ffe3ab936b624528eb3c1e4ab449 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Tue, 20 Oct 2026 09:06:13 -0500 Subject: [PATCH 2/8] XIRR counts a blank cash flow as 0; XNPV errors like Excel for blanks A cash-flow column with unused (blank) rows made XIRR return #VALUE! where Excel returns the rate. Behaviour observed in Excel on synthetic workbooks: XIRR treats a blank value as 0 and ignores a blank date next to a blank or 0 flow (a nonzero flow without a date is #NUM!). XNPV is strict: a blank value is #NUM!, and so is a blank date next to a blank or 0 value (#VALUE! next to a nonzero one). Co-Authored-By: Claude Sonnet 5.5 --- crates/functions/src/financial.rs | 45 ++++++++++++++++++++++++++----- docs/function-parity.md | 3 ++- 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/crates/functions/src/financial.rs b/crates/functions/src/financial.rs index 2758246ceb..6490efaaa2 100644 --- a/crates/functions/src/financial.rs +++ b/crates/functions/src/financial.rs @@ -237,7 +237,12 @@ fn npv(a: &[Arg], _c: &mut dyn Ctx) -> R { } /// Values and dates for XNPV/XIRR: both must be numeric and of equal length. -fn dated_flows(values: &Value, dates: &Value) -> R<(Vec, Vec)> { +/// +/// Blank cells follow what Excel returns (observed on synthetic workbooks). With `lenient` (XIRR) +/// a blank value counts as 0 and a blank date is ignored when its value is blank or 0; a nonzero +/// value without a date is `#NUM!`. XNPV is strict: a blank value is `#NUM!`, and so is a blank +/// date next to a blank or 0 value (`#VALUE!` next to a nonzero one). +fn dated_flows(values: &Value, dates: &Value, lenient: bool) -> R<(Vec, Vec)> { let va = as_array(values); let da = as_array(dates); if va.data.len() != da.data.len() { @@ -246,17 +251,22 @@ fn dated_flows(values: &Value, dates: &Value) -> R<(Vec, Vec)> { let mut v = Vec::with_capacity(va.data.len()); let mut d = Vec::with_capacity(da.data.len()); for (x, y) in va.data.iter().zip(da.data.iter()) { - match x { - Value::Number(n) => v.push(*n), + let value = match x { + Value::Number(n) => *n, + Value::Empty if lenient => 0.0, + Value::Empty => return Err(CellError::Num), Value::Error(e) => return Err(*e), _ => return Err(CellError::Value), - } + }; match y { Value::Number(n) => d.push(n.trunc()), Value::Error(e) => return Err(*e), Value::Text(_) => d.push(y.to_number()?.trunc()), + Value::Empty if lenient && value == 0.0 => continue, + Value::Empty if lenient || value == 0.0 => return Err(CellError::Num), _ => return Err(CellError::Value), } + v.push(value); } let d0 = *d.first().ok_or(CellError::Num)?; if d.iter().any(|&x| x < d0 || x < 0.0) { @@ -275,12 +285,12 @@ fn xnpv(a: &[Arg], _c: &mut dyn Ctx) -> R { if rate <= -1.0 { return Err(CellError::Num); } - let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value)?; + let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value, false)?; num_val(xnpv_calc(rate, &v, &d)) } fn xirr(a: &[Arg], _c: &mut dyn Ctx) -> R { - let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value)?; + let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value, true)?; let guess = opt_num(a, 2, 0.1)?; if !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) { return Err(CellError::Num); @@ -1795,6 +1805,29 @@ mod tests { is_err(ev("CUMIPMT", vec![n(0.01), n(360.0), n(125000.0), n(1.0), n(1.0), n(2.0)]), CellError::Num); } + #[test] + fn blank_cash_flows_follow_excel_for_xirr_and_xnpv() { + // Each result below was observed in Excel on a synthetic workbook: five rows, the first + // four -10000, 2750, 4250, 3250 on 39448, 39508, 39751, 39859; the last row varies. + let dates = col(&[39448.0, 39508.0, 39751.0, 39859.0, 39904.0]); + let gap = arr([39448.0, 39508.0, 39751.0, 39859.0].iter().map(|x| vec![nv(*x)]).chain([vec![Value::Empty]]).collect()); + let flows = |last: Value| arr([-10000.0, 2750.0, 4250.0, 3250.0].iter().map(|x| vec![nv(*x)]).chain([vec![last]]).collect()); + let rate = 0.033791377645041754; + // XIRR: a blank value counts as 0 and a blank date is ignored when its value is blank or 0. + close_tol(ev("XIRR", vec![rf(flows(Value::Empty)), rf(dates.clone())]), rate, 1e-9); + close_tol(ev("XIRR", vec![rf(flows(nv(0.0))), rf(dates.clone())]), rate, 1e-9); + close_tol(ev("XIRR", vec![rf(flows(Value::Empty)), rf(gap.clone())]), rate, 1e-9); + close_tol(ev("XIRR", vec![rf(flows(nv(0.0))), rf(gap.clone())]), rate, 1e-9); + is_err(ev("XIRR", vec![rf(flows(nv(2750.0))), rf(gap.clone())]), CellError::Num); + is_err(ev("XIRR", vec![rf(flows(tv("-"))), rf(dates.clone())]), CellError::Value); + // XNPV is strict: a blank value is #NUM! where 0 is a number. + close_tol(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(dates.clone())]), -382.66, 1e-2); + is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(dates)]), CellError::Num); + is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(gap.clone())]), CellError::Num); + is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(gap.clone())]), CellError::Num); + is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(2750.0))), rf(gap)]), CellError::Value); + } + #[test] fn cash_flows() { close_tol(ev("NPV", vec![n(0.1), n(-10000.0), n(3000.0), n(4200.0), n(6800.0)]), 1188.443412, 1e-9); diff --git a/docs/function-parity.md b/docs/function-parity.md index 2343e0de94..0a96960d2e 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -1,6 +1,6 @@ # Function parity: worksheet functions and formulas -> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (MEDIAN and AGGREGATE median avoid intermediate overflow) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-20 · **Change:** minor (XIRR counts a blank cash flow as 0 and ignores a blank date next to a blank or 0 flow, as Excel does; XNPV errors like Excel); previously minor (MEDIAN and AGGREGATE median avoid intermediate overflow) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's worksheet functions, category by category, against GridCraft's function library. Part of [target-app-parity.md](target-app-parity.md); gaps feed [gaps.md](gaps.md). @@ -114,6 +114,7 @@ workbooks; results checked in as data, not Excel files) and fixing what it finds | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | XIRR counts a blank cash-flow cell as 0 and ignores a blank date next to a blank or 0 flow, instead of returning `#VALUE!`; XNPV now returns the `#NUM!` or `#VALUE!` Excel gives for blank values and dates (observed on synthetic workbooks) | | 2026-10-15 | minor | MEDIAN and AGGREGATE median use an overflow-safe midpoint (#1579); regressions cover finite extremes, tiny values and dependent recalculation | | 2026-10-13 | minor | Clear reports changed stored cells sparsely, including those beyond the first million coordinates; dependent formulas and removed spills update, while clearing empty merges still unblocks spills (#1032) | | 2026-10-12 | minor | USDOLLAR added as a Compatibility function (not on Microsoft's list, so the counts don't change); MIRR with no positive flow is -1, COUNTIF's bare `"<="` / `">="` skip empty strings, INDIRECT with `a1` = FALSE gives `#REF!` for A1-style text (#738) | From 5e0fe2d28d6ce77099e469e8a38302f6de7398dd Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:57:26 -0500 Subject: [PATCH 3/8] XIRR: use the first nonzero cash flow for the search direction and residual A leading zero cash flow made the residual zero and the search direction wrong, so XIRR returned #NUM! for series a zero adds nothing to. --- crates/functions/src/financial.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/functions/src/financial.rs b/crates/functions/src/financial.rs index 602e45a816..3a41159819 100644 --- a/crates/functions/src/financial.rs +++ b/crates/functions/src/financial.rs @@ -316,19 +316,21 @@ fn xnpv(a: &[Arg], _c: &mut dyn Ctx) -> R { /// last digit: /// /// - Bracket the root from the guess (0 counts as 1e-5): double the rate while XNPV keeps the -/// sign it has at the guess and that sign differs from the first value (the root is higher). +/// sign it has at the guess and that sign differs from the first nonzero value (the root is higher). /// Otherwise the root is lower: bisect towards 0 if XNPV changes sign there; halve the rate /// towards 0 if XNPV is larger in size at 0 than at the guess; otherwise try minus the guess /// and then step halfway to -100% each time. A negative guess only moves towards 0 (root /// higher) or towards -100% (root lower). /// - Bisect the bracket, taking the midpoint from the upper end, until half the bracket is -/// under 1e-8 * (|rate| + 0.5) and |XNPV| is under 2e-8 * |first value|; return that +/// under 1e-8 * (|rate| + 0.5) and |XNPV| is under 2e-8 * |first nonzero value|; return that /// midpoint. A zero XNPV counts as the upper side. /// - Halving towards 0 that gets within that tolerance of 0 without a sign change goes on with /// the negative side; at most 100 XNPV evaluations in all; a rate of -100% or an XNPV that /// can't be computed (a negative base for fractional years) is #NUM!. struct XirrSolver<'a> { values: &'a [f64], + /// First nonzero value: sets the search direction and the residual scale. + first: f64, years: Vec, evals: usize, /// XNPV must be within this of 0 at the answer. @@ -363,10 +365,9 @@ impl XirrSolver<'_> { } fn solve(&mut self, guess: f64) -> R { - let first = self.values.first().copied().unwrap_or(0.0); let g = if guess == 0.0 { 1e-5 } else { guess }; let fg = self.f(g)?; - let higher = fg * first < 0.0; + let higher = fg * self.first < 0.0; if g > 0.0 { if higher { return self.double(g, fg); @@ -455,8 +456,8 @@ fn xirr(a: &[Arg], _c: &mut dyn Ctx) -> R { return Err(CellError::Num); } let d0 = d.first().copied().unwrap_or(0.0); - let first = v.first().copied().unwrap_or(0.0); - let mut solver = XirrSolver { values: &v, years: d.iter().map(|t| (t - d0) / 365.0).collect(), evals: 0, residual: 2e-8 * first.abs() }; + let first = v.iter().copied().find(|x| *x != 0.0).unwrap_or(0.0); + let mut solver = XirrSolver { values: &v, first, years: d.iter().map(|t| (t - d0) / 365.0).collect(), evals: 0, residual: 2e-8 * first.abs() }; num_val(solver.solve(guess)?) } @@ -2030,6 +2031,9 @@ mod tests { xirr_is(&[-100.0, 100.01], &[b, b + 1.0], None, 0.037_172_409_892_082_23); xirr_is(&[-100.0, 99.99], &[b, b + 1.0], None, -0.035_843_667_387_962_34); xirr_is(&[-100.0, 110.0], &[b, b + 1.0], None, 1_283_305_579_426_611.5); + // A leading zero cash flow adds nothing, so the root is the one without it (10%). The + // exact Excel answer for this input is unobserved, so only the root is checked. + assert!(matches!(xirr_of(&[0.0, -100.0, 110.0], &[b, y1, y2], None), Value::Number(r) if (r - 0.1).abs() < 1e-7)); // Dates before the first are allowed (time runs from the first date); in the second // case the search finds no sign change. xirr_is(&[-2416.93, 447.77, 1743.6], &[44331.0, 44498.0, 43849.0], None, -0.974_587_937_071_919_6); From e3fa42607fd2b27caafafc048c5b0317c9f0add8 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:31:02 -0500 Subject: [PATCH 4/8] XIRR and XNPV: match Excel for blank first rows, blank dates, text values and a zero first flow --- crates/functions/src/financial.rs | 61 ++++++++++++++++++++++++++----- docs/function-parity.md | 6 ++- 2 files changed, 56 insertions(+), 11 deletions(-) diff --git a/crates/functions/src/financial.rs b/crates/functions/src/financial.rs index 3a41159819..ba7a0027e0 100644 --- a/crates/functions/src/financial.rs +++ b/crates/functions/src/financial.rs @@ -271,20 +271,27 @@ fn dated_flows(values: &Value, dates: &Value, lenient: bool) -> R<(Vec, Vec } let mut v = Vec::with_capacity(va.data.len()); let mut d = Vec::with_capacity(da.data.len()); - for (x, y) in va.data.iter().zip(da.data.iter()) { + for (i, (x, y)) in va.data.iter().zip(da.data.iter()).enumerate() { + // Excel (XNPV): a blank or text value or a blank date is #NUM!, except in the first row, + // where it is #VALUE!. + let strict_err = if i == 0 { CellError::Value } else { CellError::Num }; let value = match x { Value::Number(n) => *n, Value::Empty if lenient => 0.0, - Value::Empty => return Err(CellError::Num), + Value::Empty => return Err(strict_err), Value::Error(e) => return Err(*e), - _ => return Err(CellError::Value), + _ if lenient => return Err(CellError::Value), + _ => return Err(strict_err), }; match y { Value::Number(n) => d.push(n.trunc()), Value::Error(e) => return Err(*e), Value::Text(_) => d.push(y.to_number()?.trunc()), - Value::Empty if lenient && value == 0.0 => continue, - Value::Empty if lenient || value == 0.0 => return Err(CellError::Num), + Value::Empty if !lenient => return Err(strict_err), + // XIRR skips a blank date next to a 0 flow and reads one in the first row as day 0. + Value::Empty if value == 0.0 => continue, + Value::Empty if i == 0 => d.push(0.0), + Value::Empty => return Err(CellError::Num), _ => return Err(CellError::Value), } v.push(value); @@ -455,6 +462,22 @@ fn xirr(a: &[Arg], _c: &mut dyn Ctx) -> R { if guess <= -1.0 || !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) { return Err(CellError::Num); } + if v.first() == Some(&0.0) { + // Excel with a 0 (or blank) first flow: the residual scale is 0, so the search just + // halves the guess towards 0 until the step is under the tolerance; a negative guess is #NUM!. + if guess < 0.0 { + return Err(CellError::Num); + } + let mut x = if guess == 0.0 { 1e-5 } else { guess }; + // Bounded: a huge guess halves to the tolerance within about 1100 steps. + for _ in 0..1100 { + if x / 2.0 < XirrSolver::tol(x / 2.0) { + break; + } + x /= 2.0; + } + return num_val(x / 2.0); + } let d0 = d.first().copied().unwrap_or(0.0); let first = v.iter().copied().find(|x| *x != 0.0).unwrap_or(0.0); let mut solver = XirrSolver { values: &v, first, years: d.iter().map(|t| (t - d0) / 365.0).collect(), evals: 0, residual: 2e-8 * first.abs() }; @@ -2031,9 +2054,16 @@ mod tests { xirr_is(&[-100.0, 100.01], &[b, b + 1.0], None, 0.037_172_409_892_082_23); xirr_is(&[-100.0, 99.99], &[b, b + 1.0], None, -0.035_843_667_387_962_34); xirr_is(&[-100.0, 110.0], &[b, b + 1.0], None, 1_283_305_579_426_611.5); - // A leading zero cash flow adds nothing, so the root is the one without it (10%). The - // exact Excel answer for this input is unobserved, so only the root is checked. - assert!(matches!(xirr_of(&[0.0, -100.0, 110.0], &[b, y1, y2], None), Value::Number(r) if (r - 0.1).abs() < 1e-7)); + // A leading zero cash flow scales the residual to 0: Excel halves the guess to a tiny + // number whatever the flows (observed), and a negative guess is #NUM!. + let z = [0.0, -100.0, 110.0]; + let zd = [b, y1, y2]; + xirr_is(&z, &zd, None, 2.980_232_238_769_531_4e-9); + xirr_is(&z, &zd, Some(0.2), 2.980_232_238_769_531_4e-9); + xirr_is(&z, &zd, Some(0.0), 4.882_812_5e-9); + xirr_is(&z, &zd, Some(5.0), 4.656_612_873_077_392_6e-9); + xirr_is(&[0.0, -100.0, 50.0], &zd, None, 2.980_232_238_769_531_4e-9); + is_err(xirr_of(&z, &zd, Some(-0.5)), CellError::Num); // Dates before the first are allowed (time runs from the first date); in the second // case the search finds no sign change. xirr_is(&[-2416.93, 447.77, 1743.6], &[44331.0, 44498.0, 43849.0], None, -0.974_587_937_071_919_6); @@ -2121,7 +2151,20 @@ mod tests { is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(dates)]), CellError::Num); is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(gap.clone())]), CellError::Num); is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(gap.clone())]), CellError::Num); - is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(2750.0))), rf(gap)]), CellError::Value); + is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(2750.0))), rf(gap)]), CellError::Num); + is_err(ev("XNPV", vec![n(0.09), rf(flows(tv("-"))), rf(dates.clone())]), CellError::Num); + // In the first row a blank value or date is #VALUE! for XNPV; XIRR reads a blank date there as day 0. + let first_row = |value: Value, date: Value| { + let cells = |x: Value, rest: [f64; 4]| arr(std::iter::once(vec![x]).chain(rest.iter().map(|y| vec![nv(*y)])).collect()); + (rf(cells(value, [2750.0, 4250.0, 3250.0, 500.0])), rf(cells(date, [39508.0, 39751.0, 39859.0, 39904.0]))) + }; + let (v0, d0) = first_row(Value::Empty, nv(39448.0)); + is_err(ev("XNPV", vec![n(0.09), v0, d0]), CellError::Value); + let (v0, d0) = first_row(nv(0.0), Value::Empty); + is_err(ev("XNPV", vec![n(0.09), v0, d0]), CellError::Value); + let (v0, d0) = first_row(nv(-10000.0), Value::Empty); + is_err(ev("XNPV", vec![n(0.09), v0.clone(), d0.clone()]), CellError::Value); + close_tol(ev("XIRR", vec![v0, d0]), 0.000_664_654_374_122_619_6, 1e-7); } #[test] diff --git a/docs/function-parity.md b/docs/function-parity.md index 6f8147058f..cad64cd1e1 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -107,7 +107,9 @@ reconstructed from observation: a sign-only search that brackets the root from t (doubling, halving towards 0, or stepping halfway to -100%) and bisects until half the bracket is under 1e-8 x (|rate| + 0.5) and XNPV is under 2e-8 x the first value, so its answer is the same midpoint as Excel's, about 1e-8 from the exact root, bit for bit in 888 of 910 synthetic cases -with an answer (97.7% agreement on 1,283 cases including `#NUM!`). Known differences: flows with +with an answer (97.7% agreement on 1,283 cases including `#NUM!`). A 0 or blank first flow +gives the tiny value Excel gives (the guess halved until the step is under the tolerance: about +2.98e-9 for the default guess, `#NUM!` for a negative guess). Known differences: flows with several sign changes where Excel returns about 3e-9 (a halving that reached 0), or `#NUM!` for two roots close to the guess. IRR uses Newton on the discount factor 1/(1+rate), at most 100 steps, stopping at a step under 1e-8; Excel's last digits differ by about 1e-12 (its exact iteration is @@ -142,7 +144,7 @@ workbooks; results checked in as data, not Excel files) and fixing what it finds | 2026-10-17 | minor | 15-significant-digit comparison moved from missing to done (#57), and the resolved caveats on the 3-D reference, dynamic-array and legacy-array rows cleared (#140, #133, #139, #156) | | 2026-10-16 | minor | FORECAST.ETS gap interpolation uses a forward-only known-point scan instead of rescanning each gap for every missing value; numerical behavior and missing-point limits are preserved (#1042) | | 2026-10-15 | minor | XIRR follows Excel's bisection (answers bit for bit, about 1e-8 from the exact root; dates before the first allowed; guess <= -1 is `#NUM!`); IRR uses Newton on the discount factor (`IRR` of -100, 19 zeros, 1E-5 is `#NUM!` like Excel; guess <= -1 is `#VALUE!`) | -| 2026-10-20 | minor | XIRR counts a blank cash-flow cell as 0 and ignores a blank date next to a blank or 0 flow, instead of returning `#VALUE!`; XNPV now returns the `#NUM!` or `#VALUE!` Excel gives for blank values and dates (observed on synthetic workbooks) | +| 2026-10-20 | minor | XIRR counts a blank cash-flow cell as 0 and ignores a blank date next to a blank or 0 flow, instead of returning `#VALUE!`; XNPV now returns the `#NUM!` Excel gives for a blank or text value or a blank date after the first row, and `#VALUE!` for a blank value or date in the first row (observed on synthetic workbooks); XIRR with a 0 or blank first flow returns Excel's tiny value (about 2.98e-9), and a first nonzero flow with a blank date reads the date as day 0 | | 2026-10-15 | minor | Iterative calculation: Maximum Iterations and Maximum Change are set in File › Options › Formulas (dropped "no Options dialog yet") | | 2026-10-15 | minor | MEDIAN and AGGREGATE median use an overflow-safe midpoint (#1579); regressions cover finite extremes, tiny values and dependent recalculation | | 2026-10-15 | minor | ADDRESS quotes a sheet name the way Excel does: names that read as an A1 cell (`A1`) or an R1C1 reference (`R1C1`, `RC`) and names starting with `.` get quotes; `TRUE` / `FALSE` stay bare (#1458) | From 2f86b52706f938f3f3d40f2b5419436958b10635 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:33:58 -0500 Subject: [PATCH 5/8] XNPV test: clone the dates range --- crates/functions/src/financial.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/functions/src/financial.rs b/crates/functions/src/financial.rs index ba7a0027e0..cc3716f03a 100644 --- a/crates/functions/src/financial.rs +++ b/crates/functions/src/financial.rs @@ -2148,7 +2148,7 @@ mod tests { is_err(ev("XIRR", vec![rf(flows(tv("-"))), rf(dates.clone())]), CellError::Value); // XNPV is strict: a blank value is #NUM! where 0 is a number. close_tol(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(dates.clone())]), -382.66, 1e-2); - is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(dates)]), CellError::Num); + is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(dates.clone())]), CellError::Num); is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(gap.clone())]), CellError::Num); is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(gap.clone())]), CellError::Num); is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(2750.0))), rf(gap)]), CellError::Num); From 9bd604aa1201f3deaa7a9c1aebd7ad0645870a71 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:45:38 -0500 Subject: [PATCH 6/8] Correct the dated_flows doc comment for blank cells --- crates/functions/src/financial.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/functions/src/financial.rs b/crates/functions/src/financial.rs index cc3716f03a..9c54775211 100644 --- a/crates/functions/src/financial.rs +++ b/crates/functions/src/financial.rs @@ -261,8 +261,9 @@ fn npv(a: &[Arg], _c: &mut dyn Ctx) -> R { /// /// Blank cells follow what Excel returns (observed on synthetic workbooks). With `lenient` (XIRR) /// a blank value counts as 0 and a blank date is ignored when its value is blank or 0; a nonzero -/// value without a date is `#NUM!`. XNPV is strict: a blank value is `#NUM!`, and so is a blank -/// date next to a blank or 0 value (`#VALUE!` next to a nonzero one). +/// value without a date is `#NUM!`, except in the first row, where the date is read as day 0. +/// XNPV is strict: a blank (or text) value or a blank date is `#NUM!`, except in the first row, +/// where it is `#VALUE!`. fn dated_flows(values: &Value, dates: &Value, lenient: bool) -> R<(Vec, Vec)> { let va = as_array(values); let da = as_array(dates); From dacff8ff9737a847fa656ee4c36d6de513dd57a2 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:10:26 -0500 Subject: [PATCH 7/8] IRR: an exact root with a zero slope is the answer, as in Excel --- crates/functions/src/financial.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/functions/src/financial.rs b/crates/functions/src/financial.rs index 9c54775211..540b9b9f05 100644 --- a/crates/functions/src/financial.rs +++ b/crates/functions/src/financial.rs @@ -499,7 +499,9 @@ fn irr_solve(v: &[f64], guess: f64) -> R { s = s * x + c; } if ds == 0.0 { - return Err(CellError::Num); + // An exact root with a zero slope (a repeated root such as {1,-2,1} at guess 0) is + // still the answer: Excel returns 0 there. + return if s == 0.0 && x > 0.0 { Ok(1.0 / x - 1.0) } else { Err(CellError::Num) }; } let next = x - s / ds; if !next.is_finite() { @@ -2094,6 +2096,10 @@ mod tests { close_tol(irr_of(&[-100.0, 300.0, -210.0], Some(0.9)), 0.887_298_334_620_741_5, 1e-12); is_err(irr_of(&[-100.0, 60.0, 60.0], Some(-1.0)), CellError::Value); close_tol(irr_of(&[-100.0, 60.0, 60.0], Some(-0.999_999)), 0.130_662_386_291_807_5, 1e-12); + // An exact repeated root at the starting guess (zero slope) is the answer, as in Excel. + assert_eq!(irr_of(&[1.0, -2.0, 1.0], Some(0.0)), Value::Number(0.0)); + assert_eq!(irr_of(&[-1.0, 3.0, -3.0, 1.0], Some(0.0)), Value::Number(0.0)); + close_tol(irr_of(&[1.0, -2.0, 1.0], None), 1.09e-7, 1e-7); } /// PMT within about 4 ULPs of Excel's (Value2 of synthetic probes; libm differs by an ULP across From 916371a2b1063ddf1611afea5066351fcde7a4c0 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:30:21 +0100 Subject: [PATCH 8/8] Drop newton and solve_rate: unused now that XIRR and IRR have their own solvers --- crates/functions/src/financial/tvm.rs | 66 --------------------------- 1 file changed, 66 deletions(-) diff --git a/crates/functions/src/financial/tvm.rs b/crates/functions/src/financial/tvm.rs index cd4626ef8a..16e1bd71db 100644 --- a/crates/functions/src/financial/tvm.rs +++ b/crates/functions/src/financial/tvm.rs @@ -152,72 +152,6 @@ pub(super) fn cumprinc(a: &[Arg], _c: &mut dyn Ctx) -> R { cumulative(a, true) } -/// Newton iteration with a numeric derivative, keeping the rate above -1. -fn newton(f: impl Fn(f64) -> f64, guess: f64) -> Option { - let mut x = guess; - for _ in 0..200 { - let y = f(x); - if !y.is_finite() { - return None; - } - let h = 1e-6 * x.abs().max(1e-3); - let d = (f(x + h) - f(x - h)) / (2.0 * h); - if d == 0.0 || !d.is_finite() { - return None; - } - let mut nx = x - y / d; - if nx <= -1.0 { - nx = (x - 1.0) / 2.0; - if nx <= -1.0 { - nx = -0.999_999_999; - } - } - if (nx - x).abs() < 1e-12 * nx.abs().max(1.0) { - return Some(nx); - } - x = nx; - } - None -} - -/// Tries Newton from the guess and a few fallback starting points; then bisection over a -/// bracket if one can be found. -fn solve_rate(f: impl Fn(f64) -> f64, guess: f64) -> R { - let check = |r: f64| f(r).is_finite() && f(r).abs() < 1e-7 * (1.0 + f(guess).abs().min(1e12)); - for g in [guess, 0.1, 0.01, 0.5, -0.5, 1.0, 0.001, 5.0, -0.9, 10.0] { - if let Some(r) = newton(&f, g) - && r > -1.0 - && check(r) - { - return Ok(r); - } - } - // Scan for a sign change and bisect. - let grid: Vec = [-0.999_999, -0.99, -0.9, -0.5, -0.2, 0.0, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 100.0, 1000.0].to_vec(); - for w in grid.windows(2) { - let (mut lo, mut hi) = match w { - [a, b] => (*a, *b), - _ => continue, - }; - let (flo, fhi) = (f(lo), f(hi)); - if !(flo.is_finite() && fhi.is_finite()) || flo * fhi > 0.0 { - continue; - } - let lo_neg = flo < 0.0; - for _ in 0..200 { - let mid = 0.5 * (lo + hi); - let fm = f(mid); - if (fm < 0.0) == lo_neg { - lo = mid; - } else { - hi = mid; - } - } - return Ok(0.5 * (lo + hi)); - } - Err(CellError::Num) -} - /// RATE's equation at rate `r`: the loan and the payments grown to the end of the term, plus /// `fv`. RATE returns the rate where it is zero. The second value is the size of its terms, to /// judge how close to zero the first can get in floating point.