Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cbrt and pow behave differently #168

Closed
fran-sgd opened this issue Feb 4, 2021 · 5 comments
Closed

cbrt and pow behave differently #168

fran-sgd opened this issue Feb 4, 2021 · 5 comments

Comments

@fran-sgd
Copy link

fran-sgd commented Feb 4, 2021

Using the cube root function:

Decimal(64).cbrt().toJSON()
< "4"

And using the pow function gives almost the same answer:

Decimal(64).pow(Decimal(1).div(3)).toJSON()
< "3.9999999999999999999"
which I work around with rounding.

But they are very different with a negative numbers:

Decimal(-64).cbrt().toJSON()
< "-4"

This is very different:

Decimal(-64).pow(Decimal(1).div(3)).toJSON()
< "NaN"

I would have expected something near -4.

I'm using v10.2.1

@MikeMcl
Copy link
Owner

MikeMcl commented Feb 4, 2021

The behaviour is the same as JavaScript numbers:

Math.cbrt(64);        // 4
Math.pow(64, 1/3)     // 3.9999999999999996
Math.cbrt(-64)        // -4
Math.pow(-64, 1/3)    // NaN

Note that Decimal(1).div(3) is not really a third.

@fran-sgd
Copy link
Author

fran-sgd commented Feb 4, 2021

Right, and right!

@fran-sgd
Copy link
Author

fran-sgd commented Feb 4, 2021

Upon reflection I guess the point is that there is no root() function, so I have to use pow() and in the case where I seek an odd integer root of a negative number (not an unreasonable thing) I have no way to do this in plain JavaScript or Decimal.js short of writing a bunch of code to detect this specific situation. I don't know if that's a worthwhile feature or not. I'm debating the utility of such a thing for my own app, which is doing user generated calculations and such a case might reasonably, albeit rarely, occur. I might just take the short route of displaying a warning when a seeking a root of a negative number, instead of telling the user that is not a number.

@MikeMcl
Copy link
Owner

MikeMcl commented Feb 4, 2021

Yes, there is an open issue #156 to add an nthroot method, but it isn't going to happen any time soon, unfortunately.

@fran-sgd
Copy link
Author

fran-sgd commented Feb 4, 2021

Ahh, perfect. Sorry, I didn't think it through to that point before posting. We decided to just let NaN go through for now since it seems so rare in our use case. Thanks!

@fran-sgd fran-sgd closed this as completed Feb 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants