Einzelnen Beitrag anzeigen

Benutzerbild von jfheins
jfheins

Registriert seit: 10. Jun 2004
Ort: Garching (TUM)
4.579 Beiträge
 
#26

Re: Quadratische Gleichungen vollständig lösen

  Alt 27. Jul 2009, 10:56
Zitat von Wolfgang Mix:
Bei Eingabe von a=1, b=2 und c=3 muß die Funktion
x1 = -1 + 1,414 i und
x2 = -1 - 1,414 i zurückliefern. Probiere das 'mal bitte!
In Ermangelung eines Delphi: Anbei der übersetzte c# Code mit Testprogramm ...

Obige Werte liefern das korrekte Ergebnis - (1,-1,-2) ebenfalls (x1=-1, x2=2)

Code:
namespace Test_2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public bool iszero(Double a)
        {
            return Math.Abs(a) < 1e-6;
        }

        public TQuadraticSolution SolveQuadratic(Double a, Double b, Double c)
        {
            TQuadraticSolution Result;

            if (iszero(b) && iszero(c))
            {
                Result.first.real = 0;
                Result.first.imaginary = 0;

                Result.second.real = 0;
                Result.second.imaginary = 0;

                return Result;
            }

            if (iszero(a))
                throw new ArgumentNullException("a", "Coefficient a must not be zero!");

            if (b * b - 4 * a * c < 0)
            {
                Double t = -0.5 * b;
                Double ti = -0.5 * Math.Sign(b) * Math.Sqrt(4 * a * c - b * b);

                Result.first.real = t / a;
                Result.first.imaginary = ti / a;

                Result.second.real = t / a;
                Result.second.imaginary = -1 * ti / a;
            }
            else
            {
                Double t = -0.5 * (b + Math.Sign(b) * Math.Sqrt(b * b - 4 * a * c));
                Result.first.real = t / a;
                Result.first.imaginary = 0;

                Result.second.real = c / t;
                Result.second.imaginary = 0;
            }
            return Result;
        }


        private void button1_Click(object sender, EventArgs e)
        {
            var solutions = SolveQuadratic((Double)numericUpDown1.Value, (Double)numericUpDown2.Value, (Double)numericUpDown3.Value);
            label1.Text = solutions.first.ToString();
            label2.Text = solutions.second.ToString();
        }
    }

    public struct TComplex
    {
        public Double real;
        public Double imaginary;

        public override String ToString()
        {
            if (imaginary < 0)
                return String.Format("{0} - {1} i", real, -imaginary);
            else
                return String.Format("{0} + {1} i", real, imaginary);
        }
    }

    public struct TQuadraticSolution
    {
        public TComplex first, second;
    }
}
Angehängte Dateien
Dateityp: exe test_2_170.exe (10,5 KB, 6x aufgerufen)
  Mit Zitat antworten Zitat