## Cube Root in OpenSCAD

Posted by Alex R English on Jun 16th 2014

A while back, I wanted to make a parametric design in OpenSCAD that required the calculation of a cube root for one of the parameters for a volume calculation, but discovered that there didn't seem to be any code for doing this in the wild. I've finally gotten around to an implementation that's about as simple to use as you could hope for.

**UPDATE** - At the time of writing, the documentation for OpenSCAD did not note that the pow function could be used for roots using fractional exponents. Given that this does work, the pow function is the preferred way to calculate arbitrary roots (cube roots included). The information in this post can still hopefully serve as a useful academic exercise demonstrating functions and recursion.

Just copy and paste this code into the top of your OpenSCAD project, or into a new document that you can include in other projects:

function calc_cube_root(n, x, j) = (j < 1 ? x : calc_cube_root(n, x *((pow(x, 3) + 2 * n) / (2 * pow(x, 3) + n)), j - 1)); function best_guess(n) = sqrt(n) / 2;

function cube_root(n, j=12) = calc_cube_root(n, best_guess(n), j);

To use the function, just call:

cube_root(x)<br>

Where x is, of course, the number you'd like to find the cube-root of. The result returned will be an APPROXIMATION of the cube root, though it should be a fairly reliably good approximation.

This function uses recursion to iterate through a function that will come up with a closer and closer approximation of the cube root (as per Halley's method as shown on the Wikipedia page for cube roots). By default, it will iterate (recurse) 12 times. You can change the number of iterations by passing the number as a second argument. Fewer iterations will calculate faster, more will be more accurate; in my brief testing, at 12 the results tended to be accurate to within six significant figures and didn't take any noticeable time to calculate.

The best_guess function creates the reasonable starting point from which to begin converging on the correct answer, it is not really even a rough approximation, but just aims to be as close as possible over the possible range of numbers for which one might seek a cube root. Division by three is often used, but over the range of numbers I was interested in, half of the square root was often a bit closer, which means fewer iterations should be necessary to reach a more correct approximation. It should be an easy task to change this calculation if there is a better operation for the range of numbers you're concerned with.

You can test the function directly by putting this line at the bottom of your project:

echo (cube_root(125));<br>

It will output
**ECHO: 5** in the compilation window (the console).

Best of luck!