@@ -2,6 +2,7 @@ |
| 2 | 2 | //! |
| 3 | 3 | //! Supports both numeric and symbolic evaluation modes. |
| 4 | 4 | |
| 5 | +use std::collections::BTreeSet; |
| 5 | 6 | use std::collections::HashMap; |
| 6 | 7 | use std::f64::consts::{E, PI}; |
| 7 | 8 | |
@@ -129,10 +130,8 @@ impl Evaluator { |
| 129 | 130 | Expr::Func(name, args) => { |
| 130 | 131 | // Symbolic functions operate on unevaluated expressions |
| 131 | 132 | match name.as_str() { |
| 132 | | - "diff" | "derivative" | "integrate" | "integral" | |
| 133 | | - "limit" | "lim" | |
| 134 | | - "solve" | "simplify" | "expand" | "factor" | |
| 135 | | - "substitute" | "subs" => { |
| 133 | + "diff" | "derivative" | "integrate" | "integral" | "limit" | "lim" |
| 134 | + | "solve" | "simplify" | "expand" | "factor" | "substitute" | "subs" => { |
| 136 | 135 | self.call_function(name, args) |
| 137 | 136 | } |
| 138 | 137 | _ => { |
@@ -163,7 +162,11 @@ impl Evaluator { |
| 163 | 162 | } |
| 164 | 163 | |
| 165 | 164 | // Symbolic operations - perform symbolic computation then try to evaluate |
| 166 | | - Expr::Derivative { expr: inner, var, order } => { |
| 165 | + Expr::Derivative { |
| 166 | + expr: inner, |
| 167 | + var, |
| 168 | + order, |
| 169 | + } => { |
| 167 | 170 | let result = Differentiator::diff_n(inner, var, *order)?; |
| 168 | 171 | let simplified = Simplifier::simplify(&result); |
| 169 | 172 | // Try to evaluate the result |
@@ -175,7 +178,12 @@ impl Evaluator { |
| 175 | 178 | } |
| 176 | 179 | } |
| 177 | 180 | |
| 178 | | - Expr::Integral { expr: inner, var, lower, upper } => { |
| 181 | + Expr::Integral { |
| 182 | + expr: inner, |
| 183 | + var, |
| 184 | + lower, |
| 185 | + upper, |
| 186 | + } => { |
| 179 | 187 | if let (Some(l), Some(u)) = (lower, upper) { |
| 180 | 188 | // Definite integral - evaluate to number |
| 181 | 189 | let result = Integrator::integrate_definite(inner, var, l, u)?; |
@@ -188,22 +196,30 @@ impl Evaluator { |
| 188 | 196 | } |
| 189 | 197 | } |
| 190 | 198 | |
| 191 | | - Expr::Limit { expr: inner, var, point, direction } => { |
| 199 | + Expr::Limit { |
| 200 | + expr: inner, |
| 201 | + var, |
| 202 | + point, |
| 203 | + direction, |
| 204 | + } => { |
| 192 | 205 | let result = Limits::limit(inner, var, point, *direction)?; |
| 193 | 206 | let simplified = Simplifier::simplify(&result); |
| 194 | 207 | self.eval(&simplified) |
| 195 | 208 | } |
| 196 | 209 | |
| 197 | | - Expr::Sum { .. } |
| 198 | | - | Expr::Product { .. } => { |
| 199 | | - if self.exact_mode { |
| 200 | | - Ok(expr.clone()) |
| 201 | | - } else { |
| 202 | | - Err(CasError::NotImplemented( |
| 203 | | - "sums/products not yet implemented".to_string(), |
| 204 | | - )) |
| 205 | | - } |
| 206 | | - } |
| 210 | + Expr::Sum { |
| 211 | + expr: inner, |
| 212 | + var, |
| 213 | + lower, |
| 214 | + upper, |
| 215 | + } => self.eval_sum(inner, var, lower, upper), |
| 216 | + |
| 217 | + Expr::Product { |
| 218 | + expr: inner, |
| 219 | + var, |
| 220 | + lower, |
| 221 | + upper, |
| 222 | + } => self.eval_product(inner, var, lower, upper), |
| 207 | 223 | |
| 208 | 224 | Expr::Inequality { lhs, op, rhs } => { |
| 209 | 225 | let lhs_val = self.eval(lhs)?; |
@@ -253,9 +269,7 @@ impl Evaluator { |
| 253 | 269 | Ok(Expr::Complex(re + x, *im)) |
| 254 | 270 | } |
| 255 | 271 | (Expr::Complex(re, im), Expr::Integer(n)) |
| 256 | | - | (Expr::Integer(n), Expr::Complex(re, im)) => { |
| 257 | | - Ok(Expr::Complex(re + *n as f64, *im)) |
| 258 | | - } |
| 272 | + | (Expr::Integer(n), Expr::Complex(re, im)) => Ok(Expr::Complex(re + *n as f64, *im)), |
| 259 | 273 | (Expr::Rational(r1), Expr::Rational(r2)) => { |
| 260 | 274 | let num = r1.num * r2.den + r2.num * r1.den; |
| 261 | 275 | let den = r1.den * r2.den; |
@@ -279,6 +293,19 @@ impl Evaluator { |
| 279 | 293 | } |
| 280 | 294 | |
| 281 | 295 | fn multiply(&self, a: &Expr, b: &Expr) -> Result<Expr> { |
| 296 | + if a.is_one() { |
| 297 | + return Ok(b.clone()); |
| 298 | + } |
| 299 | + if b.is_one() { |
| 300 | + return Ok(a.clone()); |
| 301 | + } |
| 302 | + if a.is_negative_one() { |
| 303 | + return self.negate(b); |
| 304 | + } |
| 305 | + if b.is_negative_one() { |
| 306 | + return self.negate(a); |
| 307 | + } |
| 308 | + |
| 282 | 309 | match (a, b) { |
| 283 | 310 | (Expr::Integer(x), Expr::Integer(y)) => Ok(Expr::Integer(x * y)), |
| 284 | 311 | (Expr::Float(x), Expr::Float(y)) => Ok(Expr::Float(x * y)), |
@@ -297,9 +324,10 @@ impl Evaluator { |
| 297 | 324 | let n = *n as f64; |
| 298 | 325 | Ok(Expr::Complex(re * n, im * n)) |
| 299 | 326 | } |
| 300 | | - (Expr::Rational(r1), Expr::Rational(r2)) => { |
| 301 | | - Ok(Expr::Rational(Rational::new(r1.num * r2.num, r1.den * r2.den))) |
| 302 | | - } |
| 327 | + (Expr::Rational(r1), Expr::Rational(r2)) => Ok(Expr::Rational(Rational::new( |
| 328 | + r1.num * r2.num, |
| 329 | + r1.den * r2.den, |
| 330 | + ))), |
| 303 | 331 | (Expr::Rational(r), Expr::Integer(n)) | (Expr::Integer(n), Expr::Rational(r)) => { |
| 304 | 332 | Ok(Expr::Rational(Rational::new(r.num * n, r.den))) |
| 305 | 333 | } |
@@ -455,16 +483,12 @@ impl Evaluator { |
| 455 | 483 | } |
| 456 | 484 | ("min", _, _) if !args.is_empty() => { |
| 457 | 485 | let values: Result<Vec<f64>> = args.iter().map(|a| self.to_f64(a)).collect(); |
| 458 | | - let min = values? |
| 459 | | - .into_iter() |
| 460 | | - .fold(f64::INFINITY, |a, b| a.min(b)); |
| 486 | + let min = values?.into_iter().fold(f64::INFINITY, |a, b| a.min(b)); |
| 461 | 487 | Ok(Expr::Float(min)) |
| 462 | 488 | } |
| 463 | 489 | ("max", _, _) if !args.is_empty() => { |
| 464 | 490 | let values: Result<Vec<f64>> = args.iter().map(|a| self.to_f64(a)).collect(); |
| 465 | | - let max = values? |
| 466 | | - .into_iter() |
| 467 | | - .fold(f64::NEG_INFINITY, |a, b| a.max(b)); |
| 491 | + let max = values?.into_iter().fold(f64::NEG_INFINITY, |a, b| a.max(b)); |
| 468 | 492 | Ok(Expr::Float(max)) |
| 469 | 493 | } |
| 470 | 494 | ("gcd", 2, _) => { |
@@ -489,7 +513,9 @@ impl Evaluator { |
| 489 | 513 | let result = Differentiator::diff(&args[0], var)?; |
| 490 | 514 | Ok(Simplifier::simplify(&result)) |
| 491 | 515 | } else { |
| 492 | | - Err(CasError::Type("diff requires variable as second argument".to_string())) |
| 516 | + Err(CasError::Type( |
| 517 | + "diff requires variable as second argument".to_string(), |
| 518 | + )) |
| 493 | 519 | } |
| 494 | 520 | } |
| 495 | 521 | ("diff", 3, _) | ("derivative", 3, _) => { |
@@ -498,7 +524,9 @@ impl Evaluator { |
| 498 | 524 | let result = Differentiator::diff_n(&args[0], var, *n as u32)?; |
| 499 | 525 | Ok(Simplifier::simplify(&result)) |
| 500 | 526 | } else { |
| 501 | | - Err(CasError::Type("diff requires variable and integer order".to_string())) |
| 527 | + Err(CasError::Type( |
| 528 | + "diff requires variable and integer order".to_string(), |
| 529 | + )) |
| 502 | 530 | } |
| 503 | 531 | } |
| 504 | 532 | |
@@ -508,7 +536,9 @@ impl Evaluator { |
| 508 | 536 | let result = Integrator::integrate(&args[0], var)?; |
| 509 | 537 | Ok(Simplifier::simplify(&result)) |
| 510 | 538 | } else { |
| 511 | | - Err(CasError::Type("integrate requires variable as second argument".to_string())) |
| 539 | + Err(CasError::Type( |
| 540 | + "integrate requires variable as second argument".to_string(), |
| 541 | + )) |
| 512 | 542 | } |
| 513 | 543 | } |
| 514 | 544 | ("integrate", 4, _) | ("integral", 4, _) => { |
@@ -518,7 +548,9 @@ impl Evaluator { |
| 518 | 548 | // Try to evaluate the result numerically |
| 519 | 549 | self.eval(&Simplifier::simplify(&result)) |
| 520 | 550 | } else { |
| 521 | | - Err(CasError::Type("integrate requires variable as second argument".to_string())) |
| 551 | + Err(CasError::Type( |
| 552 | + "integrate requires variable as second argument".to_string(), |
| 553 | + )) |
| 522 | 554 | } |
| 523 | 555 | } |
| 524 | 556 | |
@@ -532,18 +564,36 @@ impl Evaluator { |
| 532 | 564 | Ok(Expr::Vector(solutions)) |
| 533 | 565 | } |
| 534 | 566 | } else { |
| 535 | | - Err(CasError::Type("solve requires variable as second argument".to_string())) |
| 567 | + Err(CasError::Type( |
| 568 | + "solve requires variable as second argument".to_string(), |
| 569 | + )) |
| 536 | 570 | } |
| 537 | 571 | } |
| 538 | 572 | |
| 539 | | - ("simplify", 1, _) => { |
| 540 | | - Ok(Simplifier::simplify(&args[0])) |
| 573 | + ("sum", 4, _) => { |
| 574 | + if let Expr::Symbol(var) = &args[1] { |
| 575 | + self.eval_sum(&args[0], var, &args[2], &args[3]) |
| 576 | + } else { |
| 577 | + Err(CasError::Type( |
| 578 | + "sum requires variable as second argument".to_string(), |
| 579 | + )) |
| 580 | + } |
| 541 | 581 | } |
| 542 | 582 | |
| 543 | | - ("expand", 1, _) => { |
| 544 | | - Ok(Simplifier::simplify(&Simplifier::expand(&args[0]))) |
| 583 | + ("product", 4, _) | ("prod", 4, _) => { |
| 584 | + if let Expr::Symbol(var) = &args[1] { |
| 585 | + self.eval_product(&args[0], var, &args[2], &args[3]) |
| 586 | + } else { |
| 587 | + Err(CasError::Type( |
| 588 | + "product requires variable as second argument".to_string(), |
| 589 | + )) |
| 590 | + } |
| 545 | 591 | } |
| 546 | 592 | |
| 593 | + ("simplify", 1, _) => Ok(Simplifier::simplify(&args[0])), |
| 594 | + |
| 595 | + ("expand", 1, _) => Ok(Simplifier::simplify(&Simplifier::expand(&args[0]))), |
| 596 | + |
| 547 | 597 | ("factor", 1, _) => { |
| 548 | 598 | // Basic factoring - just return simplified for now |
| 549 | 599 | // Full factoring is complex, can add later |
@@ -553,9 +603,13 @@ impl Evaluator { |
| 553 | 603 | ("substitute", 3, _) | ("subs", 3, _) => { |
| 554 | 604 | // substitute(expr, var, replacement) |
| 555 | 605 | if let Expr::Symbol(var) = &args[1] { |
| 556 | | - Ok(Simplifier::simplify(&Simplifier::substitute(&args[0], var, &args[2]))) |
| 606 | + Ok(Simplifier::simplify(&Simplifier::substitute( |
| 607 | + &args[0], var, &args[2], |
| 608 | + ))) |
| 557 | 609 | } else { |
| 558 | | - Err(CasError::Type("substitute requires variable as second argument".to_string())) |
| 610 | + Err(CasError::Type( |
| 611 | + "substitute requires variable as second argument".to_string(), |
| 612 | + )) |
| 559 | 613 | } |
| 560 | 614 | } |
| 561 | 615 | |
@@ -565,7 +619,9 @@ impl Evaluator { |
| 565 | 619 | let result = Limits::limit(&args[0], var, &args[2], None)?; |
| 566 | 620 | self.eval(&Simplifier::simplify(&result)) |
| 567 | 621 | } else { |
| 568 | | - Err(CasError::Type("limit requires variable as second argument".to_string())) |
| 622 | + Err(CasError::Type( |
| 623 | + "limit requires variable as second argument".to_string(), |
| 624 | + )) |
| 569 | 625 | } |
| 570 | 626 | } |
| 571 | 627 | ("limit", 4, _) | ("lim", 4, _) => { |
@@ -583,7 +639,9 @@ impl Evaluator { |
| 583 | 639 | let result = Limits::limit(&args[0], var, &args[2], direction)?; |
| 584 | 640 | self.eval(&Simplifier::simplify(&result)) |
| 585 | 641 | } else { |
| 586 | | - Err(CasError::Type("limit requires variable as second argument".to_string())) |
| 642 | + Err(CasError::Type( |
| 643 | + "limit requires variable as second argument".to_string(), |
| 644 | + )) |
| 587 | 645 | } |
| 588 | 646 | } |
| 589 | 647 | |
@@ -608,7 +666,9 @@ impl Evaluator { |
| 608 | 666 | if let Expr::Matrix(rows) = &args[0] { |
| 609 | 667 | self.matrix_transpose(rows) |
| 610 | 668 | } else { |
| 611 | | - Err(CasError::Type("transpose requires a matrix argument".to_string())) |
| 669 | + Err(CasError::Type( |
| 670 | + "transpose requires a matrix argument".to_string(), |
| 671 | + )) |
| 612 | 672 | } |
| 613 | 673 | } |
| 614 | 674 | |
@@ -616,7 +676,9 @@ impl Evaluator { |
| 616 | 676 | if let Expr::Matrix(rows) = &args[0] { |
| 617 | 677 | self.matrix_trace(rows) |
| 618 | 678 | } else { |
| 619 | | - Err(CasError::Type("trace requires a matrix argument".to_string())) |
| 679 | + Err(CasError::Type( |
| 680 | + "trace requires a matrix argument".to_string(), |
| 681 | + )) |
| 620 | 682 | } |
| 621 | 683 | } |
| 622 | 684 | |
@@ -624,14 +686,18 @@ impl Evaluator { |
| 624 | 686 | if let (Expr::Matrix(a), Expr::Matrix(b)) = (&args[0], &args[1]) { |
| 625 | 687 | self.matrix_mul(a, b) |
| 626 | 688 | } else { |
| 627 | | - Err(CasError::Type("matmul requires two matrix arguments".to_string())) |
| 689 | + Err(CasError::Type( |
| 690 | + "matmul requires two matrix arguments".to_string(), |
| 691 | + )) |
| 628 | 692 | } |
| 629 | 693 | } |
| 630 | 694 | |
| 631 | 695 | ("identity", 1, Some(n)) => { |
| 632 | 696 | let n = n as usize; |
| 633 | 697 | if n == 0 || n > 100 { |
| 634 | | - return Err(CasError::EvaluationError("identity matrix size must be 1-100".to_string())); |
| 698 | + return Err(CasError::EvaluationError( |
| 699 | + "identity matrix size must be 1-100".to_string(), |
| 700 | + )); |
| 635 | 701 | } |
| 636 | 702 | let mut rows = Vec::with_capacity(n); |
| 637 | 703 | for i in 0..n { |
@@ -659,7 +725,9 @@ impl Evaluator { |
| 659 | 725 | return Err(CasError::EvaluationError("empty matrix".to_string())); |
| 660 | 726 | } |
| 661 | 727 | if rows.iter().any(|r| r.len() != n) { |
| 662 | | - return Err(CasError::EvaluationError("det requires square matrix".to_string())); |
| 728 | + return Err(CasError::EvaluationError( |
| 729 | + "det requires square matrix".to_string(), |
| 730 | + )); |
| 663 | 731 | } |
| 664 | 732 | |
| 665 | 733 | // Convert to f64 for numerical computation |
@@ -725,7 +793,9 @@ impl Evaluator { |
| 725 | 793 | return Err(CasError::EvaluationError("empty matrix".to_string())); |
| 726 | 794 | } |
| 727 | 795 | if rows.iter().any(|r| r.len() != n) { |
| 728 | | - return Err(CasError::EvaluationError("inv requires square matrix".to_string())); |
| 796 | + return Err(CasError::EvaluationError( |
| 797 | + "inv requires square matrix".to_string(), |
| 798 | + )); |
| 729 | 799 | } |
| 730 | 800 | |
| 731 | 801 | // Convert to f64 |
@@ -823,7 +893,9 @@ impl Evaluator { |
| 823 | 893 | return Err(CasError::EvaluationError("empty matrix".to_string())); |
| 824 | 894 | } |
| 825 | 895 | if rows.iter().any(|r| r.len() != n) { |
| 826 | | - return Err(CasError::EvaluationError("trace requires square matrix".to_string())); |
| 896 | + return Err(CasError::EvaluationError( |
| 897 | + "trace requires square matrix".to_string(), |
| 898 | + )); |
| 827 | 899 | } |
| 828 | 900 | |
| 829 | 901 | let mut sum = 0.0; |
@@ -851,16 +923,29 @@ impl Evaluator { |
| 851 | 923 | if b.len() != n { |
| 852 | 924 | return Err(CasError::EvaluationError(format!( |
| 853 | 925 | "matrix dimensions don't match for multiplication: {}x{} * {}x{}", |
| 854 | | - m, n, b.len(), p |
| 926 | + m, |
| 927 | + n, |
| 928 | + b.len(), |
| 929 | + p |
| 855 | 930 | ))); |
| 856 | 931 | } |
| 857 | 932 | |
| 858 | 933 | // Convert to f64 |
| 859 | | - let a_num: Vec<Vec<f64>> = a.iter() |
| 860 | | - .map(|row| row.iter().map(|e| self.to_f64(e)).collect::<Result<Vec<_>>>()) |
| 934 | + let a_num: Vec<Vec<f64>> = a |
| 935 | + .iter() |
| 936 | + .map(|row| { |
| 937 | + row.iter() |
| 938 | + .map(|e| self.to_f64(e)) |
| 939 | + .collect::<Result<Vec<_>>>() |
| 940 | + }) |
| 861 | 941 | .collect::<Result<Vec<_>>>()?; |
| 862 | | - let b_num: Vec<Vec<f64>> = b.iter() |
| 863 | | - .map(|row| row.iter().map(|e| self.to_f64(e)).collect::<Result<Vec<_>>>()) |
| 942 | + let b_num: Vec<Vec<f64>> = b |
| 943 | + .iter() |
| 944 | + .map(|row| { |
| 945 | + row.iter() |
| 946 | + .map(|e| self.to_f64(e)) |
| 947 | + .collect::<Result<Vec<_>>>() |
| 948 | + }) |
| 864 | 949 | .collect::<Result<Vec<_>>>()?; |
| 865 | 950 | |
| 866 | 951 | let mut result = Vec::with_capacity(m); |
@@ -882,6 +967,542 @@ impl Evaluator { |
| 882 | 967 | |
| 883 | 968 | Ok(Expr::Matrix(result)) |
| 884 | 969 | } |
| 970 | + |
| 971 | + fn eval_integer_bound(&self, bound: &Expr) -> Result<i64> { |
| 972 | + let value = self.eval(bound)?; |
| 973 | + match value { |
| 974 | + Expr::Integer(n) => Ok(n), |
| 975 | + Expr::Rational(r) if r.den == 1 => Ok(r.num), |
| 976 | + Expr::Float(x) => { |
| 977 | + if !x.is_finite() { |
| 978 | + return Err(CasError::Type("bound must be a finite number".to_string())); |
| 979 | + } |
| 980 | + let rounded = x.round(); |
| 981 | + if (x - rounded).abs() < 1e-10 |
| 982 | + && rounded >= i64::MIN as f64 |
| 983 | + && rounded <= i64::MAX as f64 |
| 984 | + { |
| 985 | + Ok(rounded as i64) |
| 986 | + } else { |
| 987 | + Err(CasError::Type(format!( |
| 988 | + "bound must be an integer, got {}", |
| 989 | + Expr::Float(x) |
| 990 | + ))) |
| 991 | + } |
| 992 | + } |
| 993 | + _ => Err(CasError::Type(format!( |
| 994 | + "bound must be an integer, got {value}" |
| 995 | + ))), |
| 996 | + } |
| 997 | + } |
| 998 | + |
| 999 | + fn eval_sum( |
| 1000 | + &self, |
| 1001 | + body: &Expr, |
| 1002 | + var: &crate::expr::Symbol, |
| 1003 | + lower: &Expr, |
| 1004 | + upper: &Expr, |
| 1005 | + ) -> Result<Expr> { |
| 1006 | + let inferred_var; |
| 1007 | + let active_var = if body.contains_var(var) { |
| 1008 | + var |
| 1009 | + } else { |
| 1010 | + inferred_var = Self::infer_iteration_var(body); |
| 1011 | + inferred_var.as_ref().unwrap_or(var) |
| 1012 | + }; |
| 1013 | + |
| 1014 | + match self.eval_discrete_series(body, active_var, lower, upper, false) { |
| 1015 | + Ok(value) => Ok(value), |
| 1016 | + Err(_err) => { |
| 1017 | + if let Some(symbolic) = Self::symbolic_sum(body, active_var, lower, upper) { |
| 1018 | + return Ok(Simplifier::simplify(&symbolic)); |
| 1019 | + } |
| 1020 | + |
| 1021 | + Ok(Expr::Sum { |
| 1022 | + expr: Box::new(body.clone()), |
| 1023 | + var: active_var.clone(), |
| 1024 | + lower: Box::new(lower.clone()), |
| 1025 | + upper: Box::new(upper.clone()), |
| 1026 | + }) |
| 1027 | + } |
| 1028 | + } |
| 1029 | + } |
| 1030 | + |
| 1031 | + fn eval_product( |
| 1032 | + &self, |
| 1033 | + body: &Expr, |
| 1034 | + var: &crate::expr::Symbol, |
| 1035 | + lower: &Expr, |
| 1036 | + upper: &Expr, |
| 1037 | + ) -> Result<Expr> { |
| 1038 | + let inferred_var; |
| 1039 | + let active_var = if body.contains_var(var) { |
| 1040 | + var |
| 1041 | + } else { |
| 1042 | + inferred_var = Self::infer_iteration_var(body); |
| 1043 | + inferred_var.as_ref().unwrap_or(var) |
| 1044 | + }; |
| 1045 | + |
| 1046 | + match self.eval_discrete_series(body, active_var, lower, upper, true) { |
| 1047 | + Ok(value) => Ok(value), |
| 1048 | + Err(_err) => { |
| 1049 | + if let Some(symbolic) = Self::symbolic_product(body, active_var, lower, upper) { |
| 1050 | + return Ok(Simplifier::simplify(&symbolic)); |
| 1051 | + } |
| 1052 | + |
| 1053 | + Ok(Expr::Product { |
| 1054 | + expr: Box::new(body.clone()), |
| 1055 | + var: active_var.clone(), |
| 1056 | + lower: Box::new(lower.clone()), |
| 1057 | + upper: Box::new(upper.clone()), |
| 1058 | + }) |
| 1059 | + } |
| 1060 | + } |
| 1061 | + } |
| 1062 | + |
| 1063 | + fn infer_iteration_var(body: &Expr) -> Option<crate::expr::Symbol> { |
| 1064 | + let mut vars = BTreeSet::new(); |
| 1065 | + Self::collect_symbols(body, &mut vars); |
| 1066 | + if vars.len() == 1 { |
| 1067 | + vars.into_iter().next().map(crate::expr::Symbol::new) |
| 1068 | + } else { |
| 1069 | + None |
| 1070 | + } |
| 1071 | + } |
| 1072 | + |
| 1073 | + fn collect_symbols(expr: &Expr, out: &mut BTreeSet<String>) { |
| 1074 | + match expr { |
| 1075 | + Expr::Symbol(s) => { |
| 1076 | + out.insert(s.as_str().to_string()); |
| 1077 | + } |
| 1078 | + Expr::Neg(inner) => Self::collect_symbols(inner, out), |
| 1079 | + Expr::Add(terms) | Expr::Mul(terms) | Expr::Vector(terms) => { |
| 1080 | + for term in terms { |
| 1081 | + Self::collect_symbols(term, out); |
| 1082 | + } |
| 1083 | + } |
| 1084 | + Expr::Pow(base, exp) => { |
| 1085 | + Self::collect_symbols(base, out); |
| 1086 | + Self::collect_symbols(exp, out); |
| 1087 | + } |
| 1088 | + Expr::Func(_, args) => { |
| 1089 | + for arg in args { |
| 1090 | + Self::collect_symbols(arg, out); |
| 1091 | + } |
| 1092 | + } |
| 1093 | + Expr::Derivative { expr, .. } => Self::collect_symbols(expr, out), |
| 1094 | + Expr::Integral { |
| 1095 | + expr, lower, upper, .. |
| 1096 | + } => { |
| 1097 | + Self::collect_symbols(expr, out); |
| 1098 | + if let Some(lo) = lower { |
| 1099 | + Self::collect_symbols(lo, out); |
| 1100 | + } |
| 1101 | + if let Some(hi) = upper { |
| 1102 | + Self::collect_symbols(hi, out); |
| 1103 | + } |
| 1104 | + } |
| 1105 | + Expr::Limit { expr, point, .. } => { |
| 1106 | + Self::collect_symbols(expr, out); |
| 1107 | + Self::collect_symbols(point, out); |
| 1108 | + } |
| 1109 | + Expr::Sum { |
| 1110 | + expr, lower, upper, .. |
| 1111 | + } |
| 1112 | + | Expr::Product { |
| 1113 | + expr, lower, upper, .. |
| 1114 | + } => { |
| 1115 | + Self::collect_symbols(expr, out); |
| 1116 | + Self::collect_symbols(lower, out); |
| 1117 | + Self::collect_symbols(upper, out); |
| 1118 | + } |
| 1119 | + Expr::Equation(lhs, rhs) => { |
| 1120 | + Self::collect_symbols(lhs, out); |
| 1121 | + Self::collect_symbols(rhs, out); |
| 1122 | + } |
| 1123 | + Expr::Inequality { lhs, rhs, .. } => { |
| 1124 | + Self::collect_symbols(lhs, out); |
| 1125 | + Self::collect_symbols(rhs, out); |
| 1126 | + } |
| 1127 | + Expr::Matrix(rows) => { |
| 1128 | + for row in rows { |
| 1129 | + for elem in row { |
| 1130 | + Self::collect_symbols(elem, out); |
| 1131 | + } |
| 1132 | + } |
| 1133 | + } |
| 1134 | + Expr::Integer(_) |
| 1135 | + | Expr::Rational(_) |
| 1136 | + | Expr::Float(_) |
| 1137 | + | Expr::Complex(_, _) |
| 1138 | + | Expr::Undefined |
| 1139 | + | Expr::Infinity(_) => {} |
| 1140 | + } |
| 1141 | + } |
| 1142 | + |
| 1143 | + fn symbolic_sum( |
| 1144 | + body: &Expr, |
| 1145 | + var: &crate::expr::Symbol, |
| 1146 | + lower: &Expr, |
| 1147 | + upper: &Expr, |
| 1148 | + ) -> Option<Expr> { |
| 1149 | + // Finite count for symbolic bounds: upper - lower + 1. |
| 1150 | + let count = Expr::add(vec![ |
| 1151 | + Expr::sub(upper.clone(), lower.clone()), |
| 1152 | + Expr::Integer(1), |
| 1153 | + ]); |
| 1154 | + |
| 1155 | + if !body.contains_var(var) { |
| 1156 | + return Some(Expr::mul(vec![body.clone(), count])); |
| 1157 | + } |
| 1158 | + |
| 1159 | + match body { |
| 1160 | + Expr::Symbol(s) if s == var => Some(Self::sum_linear(lower, upper)), |
| 1161 | + |
| 1162 | + Expr::Pow(base, exp) if matches!(base.as_ref(), Expr::Symbol(s) if s == var) => { |
| 1163 | + match exp.as_ref() { |
| 1164 | + Expr::Integer(0) => Some(count), |
| 1165 | + Expr::Integer(1) => Some(Self::sum_linear(lower, upper)), |
| 1166 | + Expr::Integer(2) => Some(Self::sum_square(lower, upper)), |
| 1167 | + Expr::Integer(3) => Some(Self::sum_cube(lower, upper)), |
| 1168 | + _ => None, |
| 1169 | + } |
| 1170 | + } |
| 1171 | + |
| 1172 | + Expr::Neg(inner) => Self::symbolic_sum(inner, var, lower, upper).map(Expr::neg), |
| 1173 | + |
| 1174 | + Expr::Add(terms) => { |
| 1175 | + let mut summed_terms = Vec::with_capacity(terms.len()); |
| 1176 | + for term in terms { |
| 1177 | + summed_terms.push(Self::symbolic_sum(term, var, lower, upper)?); |
| 1178 | + } |
| 1179 | + Some(Expr::add(summed_terms)) |
| 1180 | + } |
| 1181 | + |
| 1182 | + Expr::Mul(factors) => { |
| 1183 | + let (mut independent, dependent): (Vec<Expr>, Vec<Expr>) = |
| 1184 | + factors.iter().cloned().partition(|f| !f.contains_var(var)); |
| 1185 | + |
| 1186 | + if dependent.is_empty() { |
| 1187 | + independent.push(count); |
| 1188 | + return Some(Expr::mul(independent)); |
| 1189 | + } |
| 1190 | + |
| 1191 | + if dependent.len() == 1 { |
| 1192 | + let dep_sum = Self::symbolic_sum(&dependent[0], var, lower, upper)?; |
| 1193 | + independent.push(dep_sum); |
| 1194 | + return Some(Expr::mul(independent)); |
| 1195 | + } |
| 1196 | + |
| 1197 | + None |
| 1198 | + } |
| 1199 | + |
| 1200 | + _ => None, |
| 1201 | + } |
| 1202 | + } |
| 1203 | + |
| 1204 | + fn sum_linear(lower: &Expr, upper: &Expr) -> Expr { |
| 1205 | + fn triangular(x: Expr) -> Expr { |
| 1206 | + Expr::mul(vec![ |
| 1207 | + x.clone(), |
| 1208 | + Expr::add(vec![x, Expr::Integer(1)]), |
| 1209 | + Expr::Rational(Rational::new(1, 2)), |
| 1210 | + ]) |
| 1211 | + } |
| 1212 | + |
| 1213 | + let lo_minus_one = Expr::sub(lower.clone(), Expr::Integer(1)); |
| 1214 | + Expr::sub(triangular(upper.clone()), triangular(lo_minus_one)) |
| 1215 | + } |
| 1216 | + |
| 1217 | + fn sum_square(lower: &Expr, upper: &Expr) -> Expr { |
| 1218 | + fn square_sum_prefix(x: Expr) -> Expr { |
| 1219 | + let two_x_plus_one = Expr::add(vec![ |
| 1220 | + Expr::mul(vec![Expr::Integer(2), x.clone()]), |
| 1221 | + Expr::Integer(1), |
| 1222 | + ]); |
| 1223 | + Expr::mul(vec![ |
| 1224 | + x.clone(), |
| 1225 | + Expr::add(vec![x, Expr::Integer(1)]), |
| 1226 | + two_x_plus_one, |
| 1227 | + Expr::Rational(Rational::new(1, 6)), |
| 1228 | + ]) |
| 1229 | + } |
| 1230 | + |
| 1231 | + let lo_minus_one = Expr::sub(lower.clone(), Expr::Integer(1)); |
| 1232 | + Expr::sub( |
| 1233 | + square_sum_prefix(upper.clone()), |
| 1234 | + square_sum_prefix(lo_minus_one), |
| 1235 | + ) |
| 1236 | + } |
| 1237 | + |
| 1238 | + fn sum_cube(lower: &Expr, upper: &Expr) -> Expr { |
| 1239 | + fn cube_sum_prefix(x: Expr) -> Expr { |
| 1240 | + let tri = Expr::mul(vec![ |
| 1241 | + x.clone(), |
| 1242 | + Expr::add(vec![x, Expr::Integer(1)]), |
| 1243 | + Expr::Rational(Rational::new(1, 2)), |
| 1244 | + ]); |
| 1245 | + Expr::pow(tri, Expr::Integer(2)) |
| 1246 | + } |
| 1247 | + |
| 1248 | + let lo_minus_one = Expr::sub(lower.clone(), Expr::Integer(1)); |
| 1249 | + Expr::sub( |
| 1250 | + cube_sum_prefix(upper.clone()), |
| 1251 | + cube_sum_prefix(lo_minus_one), |
| 1252 | + ) |
| 1253 | + } |
| 1254 | + |
| 1255 | + fn symbolic_product( |
| 1256 | + body: &Expr, |
| 1257 | + var: &crate::expr::Symbol, |
| 1258 | + lower: &Expr, |
| 1259 | + upper: &Expr, |
| 1260 | + ) -> Option<Expr> { |
| 1261 | + let count = Expr::add(vec![ |
| 1262 | + Expr::sub(upper.clone(), lower.clone()), |
| 1263 | + Expr::Integer(1), |
| 1264 | + ]); |
| 1265 | + |
| 1266 | + if !body.contains_var(var) { |
| 1267 | + return Some(Expr::pow(body.clone(), count)); |
| 1268 | + } |
| 1269 | + |
| 1270 | + if let Some(factored) = Self::factor_simple_product_body(body, var) { |
| 1271 | + return Self::symbolic_product(&factored, var, lower, upper); |
| 1272 | + } |
| 1273 | + |
| 1274 | + match body { |
| 1275 | + Expr::Symbol(s) if s == var => Some(Self::factorial_range(lower, upper)), |
| 1276 | + Expr::Neg(inner) => { |
| 1277 | + let inner_product = Self::symbolic_product(inner, var, lower, upper)?; |
| 1278 | + Some(Expr::mul(vec![ |
| 1279 | + Expr::pow(Expr::Integer(-1), count), |
| 1280 | + inner_product, |
| 1281 | + ])) |
| 1282 | + } |
| 1283 | + Expr::Mul(factors) => { |
| 1284 | + let (independent, dependent): (Vec<Expr>, Vec<Expr>) = |
| 1285 | + factors.iter().cloned().partition(|f| !f.contains_var(var)); |
| 1286 | + |
| 1287 | + let mut parts = Vec::new(); |
| 1288 | + if !independent.is_empty() { |
| 1289 | + parts.push(Expr::pow(Expr::mul(independent), count.clone())); |
| 1290 | + } |
| 1291 | + |
| 1292 | + for dep in dependent { |
| 1293 | + parts.push(Self::symbolic_product(&dep, var, lower, upper)?); |
| 1294 | + } |
| 1295 | + |
| 1296 | + Some(Expr::mul(parts)) |
| 1297 | + } |
| 1298 | + Expr::Add(_) => Self::product_linear_term(body, var, lower, upper), |
| 1299 | + Expr::Pow(base, exp) => { |
| 1300 | + let Expr::Integer(power) = exp.as_ref() else { |
| 1301 | + return None; |
| 1302 | + }; |
| 1303 | + |
| 1304 | + if matches!(base.as_ref(), Expr::Symbol(s) if s == var) { |
| 1305 | + return Some(Expr::pow( |
| 1306 | + Self::factorial_range(lower, upper), |
| 1307 | + Expr::Integer(*power), |
| 1308 | + )); |
| 1309 | + } |
| 1310 | + |
| 1311 | + if let Some(linear_base_product) = |
| 1312 | + Self::product_linear_term(base, var, lower, upper) |
| 1313 | + { |
| 1314 | + return Some(Expr::pow(linear_base_product, Expr::Integer(*power))); |
| 1315 | + } |
| 1316 | + |
| 1317 | + None |
| 1318 | + } |
| 1319 | + _ => None, |
| 1320 | + } |
| 1321 | + } |
| 1322 | + |
| 1323 | + fn factorial_range(lower: &Expr, upper: &Expr) -> Expr { |
| 1324 | + Self::factorial_range_shifted(lower, upper, 0).unwrap_or_else(|| { |
| 1325 | + let upper_fact = Expr::func("factorial", vec![upper.clone()]); |
| 1326 | + if matches!(lower, Expr::Integer(1)) { |
| 1327 | + upper_fact |
| 1328 | + } else { |
| 1329 | + let lower_minus_one = Expr::sub(lower.clone(), Expr::Integer(1)); |
| 1330 | + let lower_fact = Expr::func("factorial", vec![lower_minus_one]); |
| 1331 | + Expr::mul(vec![upper_fact, Expr::pow(lower_fact, Expr::Integer(-1))]) |
| 1332 | + } |
| 1333 | + }) |
| 1334 | + } |
| 1335 | + |
| 1336 | + fn product_linear_term( |
| 1337 | + expr: &Expr, |
| 1338 | + var: &crate::expr::Symbol, |
| 1339 | + lower: &Expr, |
| 1340 | + upper: &Expr, |
| 1341 | + ) -> Option<Expr> { |
| 1342 | + let shift = Self::extract_linear_shift(expr, var)?; |
| 1343 | + Self::factorial_range_shifted(lower, upper, shift) |
| 1344 | + } |
| 1345 | + |
| 1346 | + fn extract_linear_shift(expr: &Expr, var: &crate::expr::Symbol) -> Option<i64> { |
| 1347 | + match expr { |
| 1348 | + Expr::Symbol(s) if s == var => Some(0), |
| 1349 | + Expr::Add(terms) => { |
| 1350 | + let mut saw_var = false; |
| 1351 | + let mut shift = 0_i64; |
| 1352 | + for term in terms { |
| 1353 | + match term { |
| 1354 | + Expr::Symbol(s) if s == var => { |
| 1355 | + if saw_var { |
| 1356 | + return None; |
| 1357 | + } |
| 1358 | + saw_var = true; |
| 1359 | + } |
| 1360 | + Expr::Integer(n) => { |
| 1361 | + shift = shift.checked_add(*n)?; |
| 1362 | + } |
| 1363 | + Expr::Neg(inner) => { |
| 1364 | + if let Expr::Integer(n) = inner.as_ref() { |
| 1365 | + shift = shift.checked_sub(*n)?; |
| 1366 | + } else { |
| 1367 | + return None; |
| 1368 | + } |
| 1369 | + } |
| 1370 | + _ => return None, |
| 1371 | + } |
| 1372 | + } |
| 1373 | + if saw_var { |
| 1374 | + Some(shift) |
| 1375 | + } else { |
| 1376 | + None |
| 1377 | + } |
| 1378 | + } |
| 1379 | + _ => None, |
| 1380 | + } |
| 1381 | + } |
| 1382 | + |
| 1383 | + fn factorial_range_shifted(lower: &Expr, upper: &Expr, shift: i64) -> Option<Expr> { |
| 1384 | + let shift_minus_one = shift.checked_sub(1)?; |
| 1385 | + if let Expr::Integer(lo) = lower { |
| 1386 | + if lo.checked_add(shift_minus_one)? < 0 { |
| 1387 | + return None; |
| 1388 | + } |
| 1389 | + } |
| 1390 | + if let Expr::Integer(hi) = upper { |
| 1391 | + if hi.checked_add(shift)? < 0 { |
| 1392 | + return None; |
| 1393 | + } |
| 1394 | + } |
| 1395 | + |
| 1396 | + let shifted_upper = |
| 1397 | + Simplifier::simplify(&Expr::add(vec![upper.clone(), Expr::Integer(shift)])); |
| 1398 | + let shifted_lower_minus_one = Simplifier::simplify(&Expr::add(vec![ |
| 1399 | + lower.clone(), |
| 1400 | + Expr::Integer(shift_minus_one), |
| 1401 | + ])); |
| 1402 | + |
| 1403 | + let upper_fact = Expr::func("factorial", vec![shifted_upper]); |
| 1404 | + if matches!(shifted_lower_minus_one, Expr::Integer(0)) { |
| 1405 | + Some(upper_fact) |
| 1406 | + } else { |
| 1407 | + let lower_fact = Expr::func("factorial", vec![shifted_lower_minus_one]); |
| 1408 | + Some(Expr::mul(vec![ |
| 1409 | + upper_fact, |
| 1410 | + Expr::pow(lower_fact, Expr::Integer(-1)), |
| 1411 | + ])) |
| 1412 | + } |
| 1413 | + } |
| 1414 | + |
| 1415 | + fn factor_simple_product_body(body: &Expr, var: &crate::expr::Symbol) -> Option<Expr> { |
| 1416 | + let Expr::Add(terms) = body else { |
| 1417 | + return None; |
| 1418 | + }; |
| 1419 | + if terms.len() != 2 { |
| 1420 | + return None; |
| 1421 | + } |
| 1422 | + |
| 1423 | + let mut has_square = false; |
| 1424 | + let mut linear_sign = 0_i64; |
| 1425 | + for term in terms { |
| 1426 | + match term { |
| 1427 | + Expr::Pow(base, exp) |
| 1428 | + if matches!(base.as_ref(), Expr::Symbol(s) if s == var) |
| 1429 | + && matches!(exp.as_ref(), Expr::Integer(2)) => |
| 1430 | + { |
| 1431 | + has_square = true; |
| 1432 | + } |
| 1433 | + Expr::Symbol(s) if s == var => linear_sign += 1, |
| 1434 | + Expr::Neg(inner) if matches!(inner.as_ref(), Expr::Symbol(s) if s == var) => { |
| 1435 | + linear_sign -= 1; |
| 1436 | + } |
| 1437 | + _ => return None, |
| 1438 | + } |
| 1439 | + } |
| 1440 | + |
| 1441 | + if !has_square { |
| 1442 | + return None; |
| 1443 | + } |
| 1444 | + |
| 1445 | + let var_expr = Expr::Symbol(var.clone()); |
| 1446 | + match linear_sign { |
| 1447 | + 1 => Some(Expr::mul(vec![ |
| 1448 | + var_expr.clone(), |
| 1449 | + Expr::add(vec![var_expr, Expr::Integer(1)]), |
| 1450 | + ])), |
| 1451 | + -1 => Some(Expr::mul(vec![ |
| 1452 | + var_expr.clone(), |
| 1453 | + Expr::add(vec![var_expr, Expr::Integer(-1)]), |
| 1454 | + ])), |
| 1455 | + _ => None, |
| 1456 | + } |
| 1457 | + } |
| 1458 | + |
| 1459 | + fn eval_discrete_series( |
| 1460 | + &self, |
| 1461 | + body: &Expr, |
| 1462 | + var: &crate::expr::Symbol, |
| 1463 | + lower: &Expr, |
| 1464 | + upper: &Expr, |
| 1465 | + is_product: bool, |
| 1466 | + ) -> Result<Expr> { |
| 1467 | + const MAX_TERMS: i64 = 100_000; |
| 1468 | + |
| 1469 | + let lo = self.eval_integer_bound(lower)?; |
| 1470 | + let hi = self.eval_integer_bound(upper)?; |
| 1471 | + |
| 1472 | + if lo > hi { |
| 1473 | + return Ok(if is_product { |
| 1474 | + Expr::Integer(1) |
| 1475 | + } else { |
| 1476 | + Expr::Integer(0) |
| 1477 | + }); |
| 1478 | + } |
| 1479 | + |
| 1480 | + let count = hi.saturating_sub(lo).saturating_add(1); |
| 1481 | + if count > MAX_TERMS { |
| 1482 | + let kind = if is_product { "product" } else { "sum" }; |
| 1483 | + return Err(CasError::EvaluationError(format!( |
| 1484 | + "{kind} has too many terms ({count}); limit is {MAX_TERMS}" |
| 1485 | + ))); |
| 1486 | + } |
| 1487 | + |
| 1488 | + let mut acc = if is_product { |
| 1489 | + Expr::Integer(1) |
| 1490 | + } else { |
| 1491 | + Expr::Integer(0) |
| 1492 | + }; |
| 1493 | + |
| 1494 | + for n in lo..=hi { |
| 1495 | + let substituted = Simplifier::substitute(body, var, &Expr::Integer(n)); |
| 1496 | + let term = self.eval(&substituted)?; |
| 1497 | + acc = if is_product { |
| 1498 | + self.multiply(&acc, &term)? |
| 1499 | + } else { |
| 1500 | + self.add(&acc, &term)? |
| 1501 | + }; |
| 1502 | + } |
| 1503 | + |
| 1504 | + Ok(Simplifier::simplify(&acc)) |
| 1505 | + } |
| 885 | 1506 | } |
| 886 | 1507 | |
| 887 | 1508 | // Helper functions |
@@ -949,6 +1570,15 @@ mod tests { |
| 949 | 1570 | } |
| 950 | 1571 | } |
| 951 | 1572 | |
| 1573 | + fn expr_to_f64(expr: &Expr) -> f64 { |
| 1574 | + match expr { |
| 1575 | + Expr::Integer(n) => *n as f64, |
| 1576 | + Expr::Rational(r) => r.to_f64(), |
| 1577 | + Expr::Float(x) => *x, |
| 1578 | + other => panic!("expected numeric expression, got {other}"), |
| 1579 | + } |
| 1580 | + } |
| 1581 | + |
| 952 | 1582 | #[test] |
| 953 | 1583 | fn test_arithmetic() { |
| 954 | 1584 | assert_eq!(eval("2 + 3").unwrap(), Expr::Integer(5)); |
@@ -1006,4 +1636,163 @@ mod tests { |
| 1006 | 1636 | let result = evaluator.eval(&expr).unwrap(); |
| 1007 | 1637 | assert_eq!(result, Expr::Integer(6)); |
| 1008 | 1638 | } |
| 1639 | + |
| 1640 | + #[test] |
| 1641 | + fn test_sum_evaluation() { |
| 1642 | + assert_eq!(eval("sum(n, n, 1, 5)").unwrap(), Expr::Integer(15)); |
| 1643 | + } |
| 1644 | + |
| 1645 | + #[test] |
| 1646 | + fn test_product_evaluation() { |
| 1647 | + assert_eq!(eval("product(n, n, 1, 4)").unwrap(), Expr::Integer(24)); |
| 1648 | + } |
| 1649 | + |
| 1650 | + #[test] |
| 1651 | + fn test_empty_discrete_range() { |
| 1652 | + assert_eq!(eval("sum(n, n, 5, 1)").unwrap(), Expr::Integer(0)); |
| 1653 | + assert_eq!(eval("product(n, n, 5, 1)").unwrap(), Expr::Integer(1)); |
| 1654 | + } |
| 1655 | + |
| 1656 | + #[test] |
| 1657 | + fn test_symbolic_solve_function() { |
| 1658 | + let result = eval("solve(x^2 - 4, x)").unwrap(); |
| 1659 | + if let Expr::Vector(solutions) = result { |
| 1660 | + assert_eq!(solutions.len(), 2); |
| 1661 | + let values: Vec<f64> = solutions |
| 1662 | + .iter() |
| 1663 | + .map(|s| match s { |
| 1664 | + Expr::Integer(n) => *n as f64, |
| 1665 | + Expr::Rational(r) => r.to_f64(), |
| 1666 | + Expr::Float(x) => *x, |
| 1667 | + other => panic!("expected numeric solution, got {other}"), |
| 1668 | + }) |
| 1669 | + .collect(); |
| 1670 | + assert!(values.iter().any(|v| (*v - 2.0).abs() < 1e-10)); |
| 1671 | + assert!(values.iter().any(|v| (*v + 2.0).abs() < 1e-10)); |
| 1672 | + } else { |
| 1673 | + panic!("expected vector of solutions"); |
| 1674 | + } |
| 1675 | + } |
| 1676 | + |
| 1677 | + #[test] |
| 1678 | + fn test_symbolic_sum_linear_closed_form() { |
| 1679 | + let symbolic = eval("sum(k, k, 1, n)").unwrap(); |
| 1680 | + let mut evaluator = Evaluator::new(); |
| 1681 | + evaluator.set_var("n", Expr::Integer(10)); |
| 1682 | + let value = evaluator.eval(&symbolic).unwrap(); |
| 1683 | + assert!((expr_to_f64(&value) - 55.0).abs() < 1e-10); |
| 1684 | + } |
| 1685 | + |
| 1686 | + #[test] |
| 1687 | + fn test_symbolic_sum_quadratic_closed_form() { |
| 1688 | + let symbolic = eval("sum(k^2 + k, k, 1, n)").unwrap(); |
| 1689 | + let mut evaluator = Evaluator::new(); |
| 1690 | + evaluator.set_var("n", Expr::Integer(5)); |
| 1691 | + let value = evaluator.eval(&symbolic).unwrap(); |
| 1692 | + assert!((expr_to_f64(&value) - 70.0).abs() < 1e-10); |
| 1693 | + } |
| 1694 | + |
| 1695 | + #[test] |
| 1696 | + fn test_symbolic_sum_fallback_for_unreduced_form() { |
| 1697 | + let symbolic = eval("sum(1/(k-1), k, 1, n)").unwrap(); |
| 1698 | + assert!(matches!(symbolic, Expr::Sum { .. })); |
| 1699 | + } |
| 1700 | + |
| 1701 | + #[test] |
| 1702 | + fn test_symbolic_product_constant_closed_form() { |
| 1703 | + let symbolic = eval("product(2, k, 1, n)").unwrap(); |
| 1704 | + let mut evaluator = Evaluator::new(); |
| 1705 | + evaluator.set_var("n", Expr::Integer(5)); |
| 1706 | + let value = evaluator.eval(&symbolic).unwrap(); |
| 1707 | + assert!((expr_to_f64(&value) - 32.0).abs() < 1e-10); |
| 1708 | + } |
| 1709 | + |
| 1710 | + #[test] |
| 1711 | + fn test_symbolic_product_factorial_closed_form() { |
| 1712 | + let symbolic = eval("product(k, k, 1, n)").unwrap(); |
| 1713 | + let mut evaluator = Evaluator::new(); |
| 1714 | + evaluator.set_var("n", Expr::Integer(5)); |
| 1715 | + let value = evaluator.eval(&symbolic).unwrap(); |
| 1716 | + assert!((expr_to_f64(&value) - 120.0).abs() < 1e-10); |
| 1717 | + } |
| 1718 | + |
| 1719 | + #[test] |
| 1720 | + fn test_symbolic_product_linear_shift_closed_form() { |
| 1721 | + let symbolic = eval("product(k+1, k, 1, n)").unwrap(); |
| 1722 | + let mut evaluator = Evaluator::new(); |
| 1723 | + evaluator.set_var("n", Expr::Integer(5)); |
| 1724 | + let value = evaluator.eval(&symbolic).unwrap(); |
| 1725 | + assert!((expr_to_f64(&value) - 720.0).abs() < 1e-10); |
| 1726 | + } |
| 1727 | + |
| 1728 | + #[test] |
| 1729 | + fn test_symbolic_product_mul_decomposition_closed_form() { |
| 1730 | + let symbolic = eval("product(2*k, k, 1, n)").unwrap(); |
| 1731 | + let mut evaluator = Evaluator::new(); |
| 1732 | + evaluator.set_var("n", Expr::Integer(5)); |
| 1733 | + let value = evaluator.eval(&symbolic).unwrap(); |
| 1734 | + assert!((expr_to_f64(&value) - 3840.0).abs() < 1e-10); |
| 1735 | + } |
| 1736 | + |
| 1737 | + #[test] |
| 1738 | + fn test_symbolic_product_simple_quadratic_factoring() { |
| 1739 | + let symbolic = eval("product(k^2 + k, k, 1, n)").unwrap(); |
| 1740 | + let mut evaluator = Evaluator::new(); |
| 1741 | + evaluator.set_var("n", Expr::Integer(4)); |
| 1742 | + let value = evaluator.eval(&symbolic).unwrap(); |
| 1743 | + assert!((expr_to_f64(&value) - 2880.0).abs() < 1e-10); |
| 1744 | + } |
| 1745 | + |
| 1746 | + #[test] |
| 1747 | + fn test_symbolic_product_telescoping_ratio() { |
| 1748 | + let symbolic = eval("product(k/(k-1), k, 2, n)").unwrap(); |
| 1749 | + let mut evaluator = Evaluator::new(); |
| 1750 | + evaluator.set_var("n", Expr::Integer(6)); |
| 1751 | + let value = evaluator.eval(&symbolic).unwrap(); |
| 1752 | + assert!((expr_to_f64(&value) - 6.0).abs() < 1e-10); |
| 1753 | + } |
| 1754 | + |
| 1755 | + #[test] |
| 1756 | + fn test_symbolic_product_fallback_for_unreduced_form() { |
| 1757 | + let symbolic = eval("product(k^2 + 2, k, 1, n)").unwrap(); |
| 1758 | + assert!(matches!(symbolic, Expr::Product { .. })); |
| 1759 | + } |
| 1760 | + |
| 1761 | + #[test] |
| 1762 | + fn test_sum_infers_iteration_var_when_template_var_unused() { |
| 1763 | + let expr = Expr::Sum { |
| 1764 | + expr: Box::new(Expr::Symbol(crate::expr::Symbol::new("n"))), |
| 1765 | + var: crate::expr::Symbol::new("i"), |
| 1766 | + lower: Box::new(Expr::Integer(1)), |
| 1767 | + upper: Box::new(Expr::Integer(5)), |
| 1768 | + }; |
| 1769 | + let result = Evaluator::new().eval(&expr).unwrap(); |
| 1770 | + assert_eq!(result, Expr::Integer(15)); |
| 1771 | + } |
| 1772 | + |
| 1773 | + #[test] |
| 1774 | + fn test_product_infers_iteration_var_when_template_var_unused() { |
| 1775 | + let expr = Expr::Product { |
| 1776 | + expr: Box::new(Expr::Symbol(crate::expr::Symbol::new("n"))), |
| 1777 | + var: crate::expr::Symbol::new("i"), |
| 1778 | + lower: Box::new(Expr::Integer(1)), |
| 1779 | + upper: Box::new(Expr::Integer(5)), |
| 1780 | + }; |
| 1781 | + let result = Evaluator::new().eval(&expr).unwrap(); |
| 1782 | + assert_eq!(result, Expr::Integer(120)); |
| 1783 | + } |
| 1784 | + |
| 1785 | + #[test] |
| 1786 | + fn test_exact_multiply_rational_one_identity() { |
| 1787 | + let mut evaluator = Evaluator::new(); |
| 1788 | + evaluator.exact_mode = true; |
| 1789 | + |
| 1790 | + let expr = Expr::mul(vec![ |
| 1791 | + Expr::Rational(crate::expr::Rational::new(1, 1)), |
| 1792 | + Expr::symbol("n"), |
| 1793 | + ]); |
| 1794 | + let result = evaluator.eval(&expr).unwrap(); |
| 1795 | + |
| 1796 | + assert_eq!(result, Expr::symbol("n")); |
| 1797 | + } |
| 1009 | 1798 | } |