0
my_fun = z^3 - 1;
my_deriv = 3*(z^2);

Those are the functions I used. I can find the real part of my solutions but when I use a function that has an imaginary part to the root such as the function above, I don't know how to find it. My code goes through different values for my initial value and if I find a root I store it in my array and if it finds a root already in the array it ignores it. So I'm basically wondering can I alter my code to find a root with an imaginary part. Thanks

clc;
close all;
clear all;

Roots = [];
Array_slot = 1;
threshold = 0.00000001;
% X_initial = 1;

for (j = -10:10)
    X_initial = j;
    if (my_deriv(X_initial) ~= 0)
    counter = 0;

    while (abs(my_fun(X_initial)) > threshold && counter < 100)
        X_initial;
%             imag(X_initial)
        X_one = X_initial - (my_fun(X_initial)/my_deriv(X_initial));
        X_initial = X_one;
%             imag(X_one)
        counter = counter + 1;

    end
    if counter < 1000
    root = (round(X_initial*1000))/1000;

        if ~ismember(root,Roots)

            Roots(Array_slot) = root;
            Array_slot = Array_slot + 1;
        end
    end
end
end

Roots
Eitan T
  • 32,660
  • 14
  • 72
  • 109
Niall Byrne
  • 53
  • 2
  • 4
  • FYI, your code fails for `z^3 - 1` as well, as it also has two imaginary roots: `0.5 * (1 ± i * sqrt(3))` – Eitan T Mar 11 '13 at 15:23
  • Yeah I knew it wasn't finding the imaginary parts aswell and that was my main problem with the code, I changed it to initialise with real and complex points, thanks – Niall Byrne Mar 11 '13 at 16:40

1 Answers1

2

Since your initial point is real, you algorithm would never leave the real axis. To find complex roots, you need to start from a complex point, for instance X_initial = 1i.

I suggest that you revise your algorithm to start once from a real point and once from a complex point, to cover the entire complex plane.

Moreover, ~ismember(root, Roots) doesn't do a great job at filtering out duplicate roots in case of floating point numbers. You'll have to come up with another way to do it. For example, compute the distance from the newly obtained root to each of the old roots, and if its close enough to one of them, it is probably a duplicate so you can discard it.

As a side note, it is recommended not use "i" and "j" as variable names to prevent unexpected behavior, especially when dealing with complex numbers.

Community
  • 1
  • 1
Eitan T
  • 32,660
  • 14
  • 72
  • 109