Strange quadratic equation c++ bug?

Hello, here is my program for solving quadratic equations:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <cmath>
#include <iostream>
using namespace std;

double quad_equation(double a, double b, double c)
{
	double x = 0;
	double delta = pow(b,2)-(4*a*c);

	if(delta < 0) return 9999; //error if sqrt less then 0

	x = ((-b)+sqrt(delta))/(2*a);

	return x;
}

int main()
{	

	double a,b,c;

	cout << "Solve a quadratic equation\n";
	cout << "Decide a: ";
	cin >> a;
	cout << "Decide b: ";
	cin >> b;
	cout << "Decide c: ";
	cin >> c;

	double x = quad_equation(a,b,c);
	cout << "The Quadratic equation for the results";
	cout << "\nResult for x: " << x << endl;
	cout << a*pow(x,2)+b*x+c; //if 0, then success


	char M; cin>> M; //keep window open
	return 0;
}


This works,
but if i write a = 2, b = 6, c = 2
then it gives a crazy result :S
This is the output:
Solve a quadratic equation
Decide a: 2
Decide b: 6
Decide c: 2
The Quadratic equation for the results
Result for x: -0.381966
2.22045e-016


This actually looks reasonable. One of the roots of 2x2 + 6x + 2 is -0.381966.

I'm guessing your question is related to the second output. If we stick this number back into the equation, we get 2.22045e-016. Why isn't this 0? The reason is that we have small rounding errors whenever we deal with floating point numbers. The only way to avoid this is to represent a number with an infinite number of bits which is impossible. Most implementations use 64 bits for a double, so that's all of the precision that we get.

In the non-computer world, this would be similar to:
1/3 = 0.333333333
3/3 = 1.000000000
3 * 1/3 should be 3/3 but: 
3 * 0.333333333 = 0.999999999 
0.999999999 != 1.0000000

so we are very close, but not quite there because we didn't use an infinite number of digits to represent 1/3.

If you want to mask that, you can use setprecision() or std::fixed from iomanip. It won't change the actual value, but it'll hide these rounding errors when outputting.
Last edited on
You function is working.

Solve a quadratic equation
Decide a: 2
Decide b: 6
Decide c: 2
The Quadratic equation for the results
Result for x: -0.381966
2.22045e-016


2.22045e-016 it's a number so little 0.0000000000000002.
I think thats almost 0.

The problem is the precision of double, you can't expect a perfect product of doubles.
http://www.wolframalpha.com/input/?i=2x%5E2+%2B+6x+%2B+2+%3D+0

Note: there are two solutions for a quadratic equation, you should return two values.
ahh ok, thanks alot :)
Topic archived. No new replies allowed.