While implementing a numerical optimization algorithm I came across some rather strange behavior in Python: after applying the Six-hump cambel back function on some values form the function's domain, some results evaluate to 'complex' numbers.
The code for evaluating a number is as simple as it can get:
def f(x1, x2):
return ((4 - 2.1 * x1 ** 2 + x1 ** (4 / 3)) * x1 ** 2 + x1 * x2 +
(-4 + 4 * x2 ** 2) * x2 ** 2)
Here are some numbers for which the above function returns a complex number:
x1 x2 Result
-1.30423635697717 -1.750915750915751 27.13078459548355-2.099189473463638j
-0.28677817116347226 0.3413919413919415 -0.20277691810793963-0.013469483248785653j
-1.105725796606031 -0.5816849816849816 0.8001125335594826-1.2106597512385535j
And some numbers for which the above functions returns a normal float:
x1 x2 Result
1 2 52.9
1.4 -2 48.04232245707135
Why exactly is this happening and what can I do to fix it?
The code is run under Python 3.3.2.
The expression x1 ** (4 / 3) is taking the variable x1 to the power of 4/3. When x1 is negative, the result of the expression has 3 roots; 2 of them are complex. Python is choosing the "principal root" for you, which is complex in this case.
See this question for ideas.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With