One thing I wish to see in languages such as PHP is to find them supporting the complex type. Complex numbers are more than vectors in 2D, and I wish to see expression containing them parsed just like the ones with real numbers. Python supports them, and you have to import ‘cmath’ to use functions of a complex variable. To import *cmath* type

import cmath

For example, complex numbers are useful in solving cubic equations even if all its roots are real. And cubic equations can be used for Bézier curve manipulations.

## Following is the Cardan formula for solving a cubic equation

Be a cubic equation.

### Step 1

Convert the equation to the form latex y^3 + py + q = 0

Use the Taylor series formula, to find a k, such that y=x-k:

Be P(x) =

Then,

Because P”(k)=0, 6k + 2a=0, thus:

.

For example,

will become

In Python:

a = -7 b = 14 c = -8 p = b - a**2 / 3. q = 2*a**3 / 27. - b*a/3. - 8

### Step 2

Find 2 numbers *u* and *v* that will help us solve the equation. If y=u+v , then the new equation will be:

We can find u,v such that (p + 3uv) = 0,

Thus,

and latex u^3 + v^3 = -q

Since p+3uv=0,

From both equations, we get that latex u^3 and latex v^3 are the roots of the quadratic equations

The roots of the quadratic equations are:

(1)

(2)

In Python, the inner root can be computed using:

innerRoot = cmath.sqrt(q**2 / 4. + p**3/27.)

Now, u and v are cubic roots of (1) and (2) respectively. They must satisfy 3uv=-p.

In Python, you get your initial *u* using:

u=(-q / 2. + innerRoot) ** (1/3.)

If the pair u,v does not satisfy 3uv = -p, you can multiply your v by

$latex-1 + i \sqrt 3 \over 2 $

until the pair satisfies the condition.

Now, having a solution, get the next by multiplying *u* by $latex-1 + i \sqrt 3 \over 2 and v by latex-1 – i \sqrt 3 \over 2

In our example:

Let’s find our three solutions:

Thus, latex $y_1 = (1.666666666666667+0j)$

Thus,

Thus,

(The above values are output from Python script. The real results look much better.)

Now, to get the roots of the original equation, add to each y.

In our example,

Thus,

Writing expressions is much easier and more readable when the language supports the complex type.