How can I calculate the square root of a Float
in C#
, similar to Core.Sqrt
in XNA?
The sqrt() function in C returns the square root of the number. It is defined in the math. h header file.
sqrt() method always returns floats, no matter what type you give it as an argument. If you need the result to be an integer, convert it back using int() .
In C programming, the sqrt() function is a pre-defined library function used to calculate the square root of a number. The sqrt() function is defined in the math. h header file.
The sqrt() function in C++ returns the square root of a number. This function is defined in the cmath header file. Mathematically, sqrt(x) = √x .
Since .net core 2.0 you can use MathF.Sqrt
.
In older versions, you can calculate it for double
and then cast back to float. May be a bit slow, but should work.
(float)Math.Sqrt(inputFloat)
Hate to say this, but 0x5f3759df seems to take 3x as long as Math.Sqrt. I just did some testing with timers. Math.Sqrt in a for-loop accessing pre-calculated arrays resulted in approx 80ms. 0x5f3759df under the same circumstances resulted in 180+ms
The test was conducted several times using the Release mode optimizations.
Source below:
/*
================
SquareRootFloat
================
*/
unsafe static void SquareRootFloat(ref float number, out float result)
{
long i;
float x, y;
const float f = 1.5F;
x = number * 0.5F;
y = number;
i = *(long*)&y;
i = 0x5f3759df - (i >> 1);
y = *(float*)&i;
y = y * (f - (x * y * y));
y = y * (f - (x * y * y));
result = number * y;
}
/*
================
SquareRootFloat
================
*/
unsafe static float SquareRootFloat(float number)
{
long i;
float x, y;
const float f = 1.5F;
x = number * 0.5F;
y = number;
i = *(long*)&y;
i = 0x5f3759df - (i >> 1);
y = *(float*)&i;
y = y * (f - (x * y * y));
y = y * (f - (x * y * y));
return number * y;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
int Cycles = 10000000;
Random rnd = new Random();
float[] Values = new float[Cycles];
for (int i = 0; i < Cycles; i++)
Values[i] = (float)(rnd.NextDouble() * 10000.0);
TimeSpan SqrtTime;
float[] Results = new float[Cycles];
DateTime Start = DateTime.Now;
for (int i = 0; i < Cycles; i++)
{
SquareRootFloat(ref Values[i], out Results[i]);
//Results[i] = (float)Math.Sqrt((float)Values[i]);
//Results[i] = SquareRootFloat(Values[i]);
}
DateTime End = DateTime.Now;
SqrtTime = End - Start;
Console.WriteLine("Sqrt was " + SqrtTime.TotalMilliseconds.ToString() + " long");
Console.ReadKey();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With