Cómo calcular la raíz cuadrada de un flotador en C #
-
30-09-2019 - |
Pregunta
¿Cómo puedo calcular la raíz cuadrada de un Float
en C#
, similar a Core.Sqrt
en XNA?
Solución
Calcular para double
y luego se echó hacia atrás para flotar. Puede ser un poco lento, pero debería funcionar.
(float)Math.Sqrt(inputFloat)
Otros consejos
Odio decir esto, pero parece tomar 0x5f3759df 3x, siempre y cuando Math.Sqrt. Acabo de hacer algunas pruebas con temporizadores. Math.Sqrt en una for-loop acceder a las matrices pre-calculado resultó en aproximadamente 80 ms. 0x5f3759df bajo las mismas circunstancias resultó en 180 + ms
La prueba se llevó a cabo varias veces usando las optimizaciones modo de lanzamiento.
Fuente continuación:
/*
================
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();
}
}
var result = Math.Sqrt((double)value);
private double operand1;
private void squareRoot_Click(object sender, EventArgs e)
{
operand1 = Math.Sqrt(operand1);
this.textBox1.Text = operand1.ToString();
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow