Define a cube root function in METAPOST

I want to draw the graph of the cube root function $f(x) = \sqrt[3]{x+1}$ by using METAPOST. However, when I use the vardef macro as follows

vardef f(expr x) = (x+1)**(1/3) enddef;


It seems to be invalid. How can we define this function in METAPOST?

• You don't say what is invalid, but clearly, the definition vardef f(expr x) = (x+1)**(1/3) enddef; does define a macro corresponding to the function x\mapsto \sqrt[3]{x+1}. For instance, f(2) is 1.44225, which is a good approximation of the cubic root of 3. Commented Apr 1, 2020 at 8:39
• I'm so sorry for this confusion. The reason is that I want to draw this function's graph, e.g. when x run from -5 to 5. I think that METAPOST does not understand f(-5) because the exponential function defined with positive values of x. Thus, I want to know is there any way in METAPOST to define a cube root function? The square root function in METAPOST is sqrt(x) but sqrt[3](x) is invalid. Commented Apr 1, 2020 at 8:49

According to your comment, the part you needed help for was to have the cube root work even for negative numbers. What about this?

vardef cuberoot(expr x) = if x < 0: -1* fi ((abs(x))**(1/3)) enddef;
vardef f(expr x) = cuberoot(x+1) enddef;

show f(-1);
show f(2);
show f(1);
show f(-3);

end


Output:

>> 0
>> 1.44225
>> 1.25992
>> -1.25992


Note: instead of if x < 0: -1* fi, you can also use if x < 0: - fi (it is possibly a tiny bit faster).

• It is absolutely wonderful. Thank you so much for your instruction. Commented Apr 1, 2020 at 9:33
• Glad to hear that. My MetaPost-fu is a bit rusty these days, but I still remember a few things. :-) Commented Apr 1, 2020 at 9:34