emufossum13
emufossum13

Reputation: 407

Quadratic Formula returning an error

I'm working on a program, and I'm using the quadratic formula. This is the code that executes when a button is clicked, to solve the problem,

private void button1_Click(object sender, EventArgs e)
{
    double aVal, bVal, cVal, xVal1, xVal2;
    xVal1 = 0;
    xVal2 = 0;
    aVal = Convert.ToDouble(a.Text);
    bVal = Convert.ToDouble(b.Text);
    cVal = Convert.ToDouble(c.Text);
    xVal1 = (bVal + Math.Sqrt(Math.Pow(bVal, 2) - (4 * aVal * cVal))) / 2 * aVal; //Positive Calculation
    xVal2 = (bVal - Math.Sqrt(Math.Pow(bVal, 2) - (4 * aVal * cVal))) / 2 * aVal; //Negative Calculation
    xPos.Text = Convert.ToString(xVal1);
    xNeg.Text = Convert.ToString(xVal2);
}

After some debugging, I believe I've narrowed the issue down to line 9 and 10, where the actual math takes place. However, I'm not quite sure what's wrong. As you can see, the numbers are doubles, and are initialized, so they are not null, or truncating. When I run the program and input a b and c values of say, 6, 4, and 3, the xPos and xNeg labels which are responsible for outputting the negative and positive values, simply display NaN. Should I be using a label for this sort of thing?

Upvotes: 4

Views: 125

Answers (2)

Enigmativity
Enigmativity

Reputation: 117175

The result of Math.Pow(bVal, 2) - (4 * aVal * cVal) is -56 for the input values of 6, 4, and 3. When you obtain the Sqrt of a negative you get the result NaN.

You also need to use the correct formula. You should have:

var sqrt = Math.Sqrt(Math.Pow(bVal, 2.0) - (4.0 * aVal * cVal));
var xVal1 = (-bVal + sqrt) / (2.0 * aVal); //Positive Calculation
var xVal2 = (-bVal - sqrt) / (2.0 * aVal); //Negative Calculation

Note the - in front of the first bVal and the brackets around the 2 * aVal.

I've also expressed the constants with a .0 as this tells the compiler that you are using doubles. It is quite easy to get incorrect results if you do not do this.

Upvotes: 6

Rezo Megrelidze
Rezo Megrelidze

Reputation: 3060

    public static double[] SolveQuadratic(double a, double b, double c)
    {
        return new[]
        {
            (-b + Math.Sqrt(b*b - 4*a*c))/2*a,
            (-b - Math.Sqrt(b*b - 4*a*c))/2*a
        };
    }

Then do just:

        double x1Val = SolveQuadratic(a, b, c)[0];
        double x2Val = SolveQuadratic(a, b, c)[1];

        textX1.Text = x1Val.ToString();
        textX2.Text = x2Val.ToString();

Upvotes: 0

Related Questions