Skip to content

feat: perfect cube#122

Merged
raklaptudirm merged 2 commits intoTheAlgorithms:masterfrom
zFlxw:feat/perfect-cube
Apr 6, 2023
Merged

feat: perfect cube#122
raklaptudirm merged 2 commits intoTheAlgorithms:masterfrom
zFlxw:feat/perfect-cube

Conversation

@zFlxw
Copy link
Copy Markdown
Contributor

@zFlxw zFlxw commented Apr 3, 2023

Implementation of a perfect cube.

Copy link
Copy Markdown
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
Copy Markdown
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