• Advertisement
Sign in to follow this  

Quadratic Formula -1#ind?

This topic is 1657 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, about a week ago I made a program that calculated quadratic formulas. Now, I'm supposed to change that program and use a function to the calculations. Problem is, it prints both x1 and x2 as "-1.#IND".

 

I've googled around and apparently it happens when you divide by zero, but a isn't 0.

#include "../../std_lib_facilities.h"

void quadratic(double a, double b, double c){ // Calculate and print x
	double x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 *a);
		cout << "X1 == " << x1 << endl;
	double x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 *a);
		cout << "X2 == " << x2 << endl;
}

int main()
{
	double a = 1, b = 1, c = 1;	// Input loop
	cout << "This program will help you solve ax (squared) + bx + c = 0\nEnter a, b and c\n";
	while (cin >> a && cin >> b && cin >> c)
		quadratic(a, b, c);
}

Share this post


Link to post
Share on other sites
Advertisement

It can also happen if you take the square root of a negative number, which happens if your polynomial doesn't have any real roots.

Share this post


Link to post
Share on other sites

Also if a may be zero (straight line), then you need to handle that because the "/ (2 * a)" becomes divide by zero.

Share this post


Link to post
Share on other sites

The more usual way would be to just take the contents of sqrt, calculate it and check it for negative.

assert(a != 0);//if may be true, do something about it
double d = b * b - 4 * a * c;
if (d < 0)
{
    return; //no root
}

double dSqrt = std::sqrt(d);

double x1 = (-b + dSqrt) / (2 * a);
double x2 = (-b - dSqrt) / (2 * a);
Edited by SyncViews

Share this post


Link to post
Share on other sites

Well it doesn't really miss the solution, it just prints the same one out twice, and SyncView's code carries on if d == 0.

 

SyncView later storing sqrt(d) in an int isn't a great plan though ;)

Share this post


Link to post
Share on other sites

Fixed :) . Fortunately most compilers will warn about a double to int implicit conversion.

 

While d == 0 in some cases is useful, I think in practice most of the time your going to end up with just being near zero due to rounding errors at various stages, including the inputs them selves. If the single root situation is of interest for whatever you are doing, you will need to decide how close is close enough.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement