Skip to content

Commit

Permalink
Fix bug where combine like factors turns -1 * -1 into (-1)^2, prefer …
Browse files Browse the repository at this point in the history
…1 instead
  • Loading branch information
ElectrifyPro committed Oct 10, 2023
1 parent 182676d commit 0b5beec
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
9 changes: 9 additions & 0 deletions cas-math/src/algebra/simplify/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,15 @@ mod tests {
assert_eq!(simplified_expr, Expr::Primary(Primary::Number(float(1))));
}

#[test]
fn combine_like_factors_mul_numbers() {
let input = String::from("-1 * -1 * 2 * 2");
let expr = Parser::new(&input).try_parse_full::<AstExpr>().unwrap();
let math_expr = Expr::from(expr);
let simplified_expr = simplify(&math_expr);
assert_eq!(simplified_expr, Expr::Primary(Primary::Number(float(4))));
}

#[test]
fn complicated_combine_like_factors() {
let input = String::from("3p^-5q^9r^7/(12p^-2q*r^2)");
Expand Down
12 changes: 6 additions & 6 deletions cas-math/src/algebra/simplify/rules/multiply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,17 +156,17 @@ pub fn combine_like_factors(expr: &Expr, step_collector: &mut dyn StepCollector<
while next_factor_idx < new_factors.len() {
let (next_factor, next_factor_exp) = get_exp(&new_factors[next_factor_idx]);

if current_factor == next_factor {
// bases must be strictly equal
// if they are, apply a^b*a^c = a^(b+c)
current_factor_exp += next_factor_exp;
new_factors.swap_remove(next_factor_idx);
} else if current_factor_exp == next_factor_exp
if current_factor_exp == next_factor_exp
&& current_factor.is_number() && next_factor.is_number() {
// degrees must be strictly equal
// if they are, apply a^c*b^c = (a*b)^c
current_factor *= next_factor;
new_factors.swap_remove(next_factor_idx);
} else if current_factor == next_factor {
// bases must be strictly equal
// if they are, apply a^b*a^c = a^(b+c)
current_factor_exp += next_factor_exp;
new_factors.swap_remove(next_factor_idx);
} else {
next_factor_idx += 1;
}
Expand Down

0 comments on commit 0b5beec

Please sign in to comment.