cortex-js / compute-engine

An engine for symbolic manipulation and numeric evaluation of math formulas expressed with MathJSON
https://cortexjs.io
MIT License
356 stars 42 forks source link

Substitution and negative power returns wrong result #159

Closed truebluepl closed 2 months ago

truebluepl commented 4 months ago

Description

Substitution of x and negative power returns wrong result.

Steps to Reproduce

const ce = new ComputeEngine.ComputeEngine();

//x=3/7 let a = ce.parse('\frac{x^{-1}}{9}').subs({ x: ce.parse('\frac{3}{7}'), });

//x=3/7 but included in expression let b = ce.parse('\frac{(\frac{3}{7})^{-1}}{9}'); console.log(a,b);

Actual Behavior

Substitution returns 21.

Expected Behavior

Should returns 7/27.

arnog commented 4 months ago

I can't reproduce this. I'm getting 7/27 as the answer, as expected.

truebluepl commented 4 months ago

Hmm... I've prepares fiddle: https://jsfiddle.net/uprwaxj7/

Here is screenshot. At bottom right corner is console output: image

arnog commented 4 months ago

OK, I think this is a duplicate of #147. I can't reproduce the problem with top of tree.

truebluepl commented 4 months ago

I think there is a problem when the power of the numerator is exactly -1 (when we deal with fraction). I made some test:

//wrong, result=8, should be 0.5
let a = ce.parse('\\frac{x^{-1}}{4}').subs({
  x: ce.parse('0.5'),
}).N().value;
console.log(a);

//wrong, result=1, should be 0.25
let b = ce.parse('\\frac{x^{-1}}{2}').subs({
  x: ce.parse('2'),
}).N().value;
console.log(b);

//ok
let c = ce.parse('x^{-1}').subs({
  x: ce.parse('2'),
}).N().value;
console.log(c);

//ok
let d = ce.parse('\\frac{2}{x^{-1}}').subs({
  x: ce.parse('2'),
}).N().value;
console.log(d);

//ok
let e = ce.parse('\\frac{x^{-2}}{x^{-1}}').subs({
  x: ce.parse('2'),
}).N().value;
console.log(e);

//ok
let f = ce.parse('\\frac{x^{-2}}{4}').subs({
  x: ce.parse('2'),
}).N().value;
console.log(f);

//ok
let g = ce.parse('\\frac{x^{-3}}{4}').subs({
  x: ce.parse('2'),
}).N().value;
console.log(g);
arnog commented 2 months ago

Verified these all work with TOT.

truebluepl commented 2 months ago

Hello! What do you mean by TOT? I prepared those examples using JSFiddle: https://jsfiddle.net/dxr6u7La/ Still with bugs...

arnog commented 2 months ago

TOT is top of tree, the latest HEAD in github.