Skip to content

feat: perfect cube #122

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

Merged
merged 2 commits into from
Apr 6, 2023
Merged

Conversation

zFlxw
Copy link
Contributor

@zFlxw zFlxw commented Apr 3, 2023

Implementation of a perfect cube.

Copy link
Contributor

@appgurueu appgurueu left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately, it doesn't work like this due to floating point error: 1/3 can not be precisely represented as a float. Thus Math.pow(x, 1/3), no matter how well it is implemented, will only ever give you an approximation to the correct cube root. Additionally, Math.pow will always approximate the solution (f.E. it may, theoretically, use taylor series for this), so there will be another error margin.

You could (presumably) mitigate this by using Math.round(n**(1/3))**3 == n instead.

Here's a small snippet to verify this:

for (let i = 0; i < 1000; i++) { if (!perfectCube(i*i*i)) console.log(i*i*i) }

Even rather small numbers like 64 will be erroneously classified as imperfect cubes.

@zFlxw
Copy link
Contributor Author

zFlxw commented Apr 4, 2023

Unfortunately, it doesn't work like this due to floating point error: 1/3 can not be precisely represented as a float.

Oh yes, thank you, I didn't think about this floating point approximation. I've implemented and tested your suggestion, as well as some new test cases for higher numbers that would be wrong with the former implementation.

@zFlxw zFlxw requested a review from appgurueu April 4, 2023 09:11
@raklaptudirm raklaptudirm merged commit ee9727f into TheAlgorithms:master Apr 6, 2023
@zFlxw zFlxw deleted the feat/perfect-cube branch April 6, 2023 19:13
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

Successfully merging this pull request may close these issues.

3 participants