# Having trouble with the sqrt() function.

• 11-01-2005
SlyMaelstrom
Having trouble with the sqrt() function.
I'm getting strage output with the sqrt() function in a quadratic formula program. I'll also add that I had the same problem using pow(x,.5). It's definitely the function that's causing the problem, I've made sure of it.

Code:

```#include <iostream> #include <iomanip> #include <cmath> using namespace std; void quad(double, double, double, double&, double&); int main() {     double a, b, c, x1, x2;         cout.setf(ios::fixed, ios::floatfield);     cout.setf(ios::showpoint);     cout << "Enter the values of A, B, and C for the quadratic equation."         << "\n>";     cin >> a >> b >> c;     cin.ignore(3,'\n');     quad(a,b,c,x1,x2);         cout << setprecision(2) << "X = " << x1 << " or " << x2 << ".";     cin.get();         return 0;    } void quad(double a, double b, double c, double& xPos, double& xNeg) {          if (2*a != 0 && (b*b - 4*a*c) < 0) {         xPos = (-b + sqrt(b*b - 4*a*c))/(2*a);         xNeg = (-b - sqrt(b*b - 4*a*c))/(2*a);            }     else {         xPos = 0;         xNeg = 0;            }              return;     }```
Output:
Code:

```Enter the values of A, B, and C for the quadratic equation. >3 4 5 X = -1.#J or -1.#J.```
• 11-01-2005
Daved
b is 4. b*b is 16. a is 3, c is 5. 4*3*5 is 60. 16-60 is -44. You are taking the square root of a negative number.

The < in your if should probably be >.

A better test case might be 1 -5 6.
• 11-01-2005
SlyMaelstrom
Hey, good call. A can't believe a genuine typo wasted 15 minutes of my life. What's the garbage that sqrt() returns if you attemp to take the sqrt of a negetive number. I know it's impossible in real life, but how does a computer come to the answer -.#J?
• 11-01-2005
Enahs
Quote:

I know it's impossible in real life, but how does a computer come to the answer -.#J?
It is not impossible.
It is called ‘i’ which is short for imaginary.
‘i’ is just the square root of negative one.
Square root of -1 X square root of 4 is the same thing as the square root of -4.
Square root of 4 is two, square root of -1 is i, so the square root of -4 = 2i

You could just check what is under the root, if it is less than 0 then take the absolute value of it (meaning positive) evaluate the square root and tack on a ‘i’ to it.

I think the result is just a general error/problem message.
• 11-02-2005
SlyMaelstrom
Yes, I know the value 'i', but I was refering of the spectrum of real numbers. The computer can't find a real number answer so it spits out garbage. ...but where does it find the garbage?
• 11-02-2005
Daved
Since sqrt is only defined to work with non-negative numbers, you cannot expect valid output when you use it incorrectly. However, that isn't really garbage, that is probably just your implementation's way of expressing NaN (not a number).