[英]How to Calculate the Square Root of a Float in C#
如何在C#
計算Float
平方根,類似於XNA中的Core.Sqrt
?
將其計算為double
,然后將其轉換為float。 可能有點慢,但應該工作。
(float)Math.Sqrt(inputFloat)
討厭這樣說,但0x5f3759df似乎需要3倍於Math.Sqrt。 我只是對計時器進行了一些測試。 for循環訪問預先計算的數組中的Math.Sqrt導致大約80ms。 在相同情況下0x5f3759df導致180 + ms
使用Release模式優化進行了多次測試。
來源如下:
/*
================
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.