Return value of math.sqrt

1.5k views Asked by At

I have been try to draw the function of y^2=4*a*x but I have run into a problem. when I use the math.sqrt function to find the square root of a value which has two answer +or- something i only get the positive value. i.e if i found the sqrt of 4 it would return +2 instead of + or -2.

Any help would be deeply appreciated.

4

There are 4 answers

0
Pierre-Luc Pineault On

If you read the doc (MSDN is really complete and well made, use it before asking questions) you will see that with a parameter 0 or positive, Math.Sqrt returns only "The positive square root of d."

If you need the negative value, you have to do it yourself, for example like this :

double value = 4;
double positiveSqrt = Math.Sqrt(value);
double negativeSqrt = positiveSqrt * -1;
0
Dustin Kingen On

You can write your own method to return both values:

public static IEnumerable<double> Sqrt(double d)
{
    var result = Math.Sqrt(d);
    yield return result;
    yield return -result;
}
0
FelProNet On

You can multiply the answer with -1 also and get both.

2
p.s.w.g On

If you really want a function that returns both positive and negative square roots, you could write your own pretty easily:

public static double[] Sqrts(double d) {
    var v = Math.Sqrt(d);
    return v == 0 ? new[] { v } : new[] { v, -v };
}