jiggzson / nerdamer

a symbolic math expression evaluator for javascript
http://www.nerdamer.com
MIT License
517 stars 82 forks source link

Problems with fractional powers (when I build function) #561

Closed MAGNETO903 closed 3 years ago

MAGNETO903 commented 4 years ago

I have a simple expression log(x)^(1/3) (1) which is equivalent cbrt(log(x)) (2)

I built expression (1) var f = nerdamer("log(x)^(1/3)").buildFunction() and then tried to use it

console.log(f(0)) // Infinity
console.log(f(0.2)) // NaN
console.log(f(0.99)) // NaN

it fails

But when I build expression (2) var f2 = nerdmamer("cbrt(log(x))").buildFunction() and tested

console.log(f2(0)) // -Infinity
console.log(f2(0.2)) // -1.17190230687955
console.log(f2(0.99)) // -0.2158043485359359

that's right

MAGNETO903 commented 4 years ago

Thats occurs, because Math.pow(n, x) cant calculate when n<0 and x<1.

var f = nerdamer("log(x)^(1/3)").buildFunction();
console.log(f.toString()) 
// function anonymous(x
//) {
// return Math.pow(Math.log(x),0.3333333333333333333333333333333333333333333333333333333333333333333333333333333);
//}

So, I can write my own nthRoot(n, x) and say nerdamer to use nthRoot(n, x) instead of Math.pow()

jiggzson commented 4 years ago

@MAGNETO903. yes you can. You can define your own function name nthRoot function but make sure you also define it's numeric equivalent within the Math2 object. I'll try to provide an example soon.

jiggzson commented 3 years ago

@MAGNETO903, was your issue resolved?

MAGNETO903 commented 3 years ago

@jiggzson, no, Unfortunatly

jiggzson commented 3 years ago

@MAGNETO903, here's an interesting observation. You get the same issue when using Wolfram Alpha.

Here's log(x)^(1/3) and here's cbrt(log(x)). Wolfram Alpha gives a complex value for one and not the other.