如何计算 a Float
in的平方根C#
,类似于Core.Sqrt
在 XNA 中?
问问题
49923 次
4 回答
15
计算它,double
然后再转换为浮点数。可能有点慢,但应该可以。
(float)Math.Sqrt(inputFloat)
于 2010-12-03T21:10:29.603 回答
6
讨厌这么说,但 0x5f3759df 似乎需要 Math.Sqrt 的 3 倍。我只是用计时器做了一些测试。访问预先计算的数组的 for 循环中的 Math.Sqrt 大约需要 80 毫秒。0x5f3759df 相同情况下导致180+ms
使用发布模式优化进行了多次测试。
以下来源:
/*
================
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();
}
}
于 2013-02-28T21:44:35.597 回答
0
var result = Math.Sqrt((double)value);
于 2010-12-03T21:12:20.947 回答
-5
private double operand1;
private void squareRoot_Click(object sender, EventArgs e)
{
operand1 = Math.Sqrt(operand1);
this.textBox1.Text = operand1.ToString();
}
于 2015-10-13T14:41:25.123 回答