You are getting problems because a negative number raised to a fractional power can be a complex number.
The solution is to apply a math identity. We know that if x is negative, then x1/3 is equal to −((−x)1/3). In other words, we turn x into a positive number, take the cube root, and negate it again. Here is the Python code to do so:
def h(x):
if x >= 0:
return -1.0 / x**(1.0/3.0)
else: # x < 0
return -h(-x)
To explain why you are getting the problem in the first place, it helps to look at the implementation of x**y
(the power operator). The key mathematical identity is that xy = exp(log(x) · y). This identity makes it easier to handle powers, because the exponent is treated as a regular number and doesn't need to be analyzed (is it an integer? is it a fraction? is it negative? etc.).
When x is a positive number, log(x) is a real number. As long as y is also a real number, exp(log(x) · y) will be a real number.
But when x is a negative number, log(x) is a complex number. Specifically, it is equal to [log(-x) + π · i]. When we multiply such a complex number by y and then apply exp(), the result will usually be a complex number - which is not what you hoped for.