问题
Just wondering, is it possible to compute the square roots of negative numbers in C#? For example sqrt(-1) = i.
I wrote this piece of code:
using System;
public static class sqrts
{
public static void Main()
{
string x;
double sqrtofx;
Console.Write("Enter a number: ");
x = Console.ReadLine();
sqrtofx = Math.Sqrt(Convert.ToInt32(x));
Console.WriteLine("\nSqrt({0}): {1}", x, sqrtofx);
Console.ReadKey();
}
}
If I enter 25, it gives 5. However, if I put in -5, it gives NaN instead of 5i.
回答1:
There is a Complex struct that should do what you need:
Complex c = Complex.Sqrt(-25); // has a value of approximately 0 + 5i
(There's an implicit conversion from most number types, including int
, to Complex
. It works how you'd probably expect: the number is taken as the real part, and the imaginary part is 0. This is how -25
is a valid parameter to Complex.Sqrt(Complex)
.)
回答2:
Use the implemented Complex Structure of C#: http://msdn.microsoft.com/en-us/library/system.numerics.complex.aspx
Complex c = new Complex(-1,0);
Complex result = Complex.Sqrt(c);
http://msdn.microsoft.com/en-us/library/system.numerics.complex.sqrt.aspx
回答3:
double
(or int
, long
, short
, or any other built in numeric type) isn't built to support non-real numbers. There are libraries in existence that are built to support any complex number, but in exchange for that added functionality they consume more space and operations on them are much slower. Since so much of the field has a demand for computations on real numbers it's not reasonable to add these costs to these most basic numeric types.
回答4:
That's because square roots of negative numbers produce complex numbers. In more basic and general mathematics square root is assumed to only apply to positive numbers. Either take the square root of the absolute value of your numbers or use the Complex
data type and it's square root function. What you decide depends on what you aim to achieve.
回答5:
or you could simply do that
public static float Root(float value)
{
int negative = 1;
if(value < 0)
negative = -1;
return Math.Sqrt(Math.Abs(value)) * negative;
}
then you can use this function everytimes you need to root without being afraid
this should be much less heavy than Complex and you have a good control over it.
回答6:
Why not just check if negative first, and if it is, multiply by (-1) and add i
to the output?
来源:https://stackoverflow.com/questions/18923247/square-root-of-negative-numbers