The problem is simple. If we look at this area of the horseshoe, we get imaginary numbers. For part of it, this must belong to our heart. In this area, if we were to evaluate our function (in mathematics, but not in programming), the imaginary part of the function was canceled. Therefore, it should look like this (created in Mathematica):

In principle, the function for this part is almost identical; we just have to do arithmetic with complex numbers instead of real numbers. Here's a function that does just that:
private static double topOfHeart(double x, double y, double temp, double temp1) {
To join this program, simply modify it to reflect this:
if (temp1 < 0) { return topOfHeart(x, y, temp, temp1); }
And running it, we get the desired result:

It should be pretty clear that this new function implements exactly the same formula. But how does each part work?
double[] temp3 = cbrt_complex(temp, sqrt(-temp1));
cbrt_complex takes a complex number in the form a + bi . So the second argument is just sqrt(-temp1) (note that temp1 < 0 , so I use - instead of Math.abs ; Math.abs is probably the best idea). cbrt_complex returns the cube root of a complex number, in polar form: re iθ . We can see from wolframalpha that with positive r and θ we can write the nth root of complex numbers as follows
![MathJax: \ sqrt [n] r \, e ^ {i \ left (2 \ pi \ left \ lfloor \ frac {\ pi- \ theta} {2 \ pi} \ right \ rfloor + \ theta \ right)}](https://fooobar.com/undefined)
And this is exactly how the code for cbrt_complex and sqrt_complex . Note that both have a complex number in rectangular coordinates ( a + bi ) and return a complex number in polar coordinates ( re iθ )
double[] part1 = polar_reciprocal(temp3);
It is easier to take the inverse polar complex number than a rectangular complex number. If we have re iθ , then its inverse (this, fortunately, corresponds to the standard power rules) is simply 1/re -iθ . That is why we remain in polar form; the polar form simplifies operations like multiplication, and operations like input are more complicated, and the rectangular form is vice versa.
Note that if we have a polar complex number re iθ and we want to multiply by a real number d , the answer will be as simple as dre iθ .
The toRect function does exactly what it seems: it converts complex complex coordinate numbers into rectangular coordinate complex numbers.
You may have noticed that the if statement does not check for an imaginary part, but only if the imaginary part is really small. This is due to the fact that we use floating point numbers, so checking result[1] == 0 will most likely fail.
And here you are! Please note that we could implement the whole function of the heart with this complex arithmetic of numbers, but it is probably faster to avoid it.