Imaginary number comparison with C#

86 views Asked by At

I want to analyse a polynomial and only output the real roots. I use the Systems.Numerics to get the complex number and then compare their imaginary component to a set value to find out if they are real. To analyse the polynom, I use MathNet.Numerics for the analysis. The outputs should later be processed and printed out, but for testing reasons, I also print out the full complex number.

This is my code:

Complex[] roots = func.Roots();

List<double> realroots = new List<double>();

// Complex[] rootsDis = roots.Distinct().ToArray();
foreach (var root in roots)
{
    if (root.Imaginary == 0)
    {
        string Root = root.Real.ToString();
        double.TryParse(Root, out double RealRoot);
        realroots.Add(RealRoot);
        Ausgabe.Items.Add(root.ToString());
    }
    else
    {
        Ausgabe.Items.Add("no real roots");
        return;
    }
}

My problem is, that even if the imaginary component is 0 when printed out, the if statement is not fulfilled an also inserting conditions like >0,001 does not help either (I did the same in python once and used numpy, there it helped). What can I do to correct that?

Edit: I solved it by deleting the return in the else statement. What i didnt grasp was, that a foreach loop goes through the array one by one and my programm failed becaus it broke the loop when it found the first non real root. But, thanks for your help nonetheless, I learend some things from it.

1

There are 1 answers

0
tmaj On

Could you compare with some calibrated epsilon?

For example:

if (Math.Abs(root.Imaginary) < 0.0000001)
{
   // This is real!
}