简体   繁体   English

如何计算C#中浮点的平方根

[英]How to Calculate the Square Root of a Float in C#

如何在C#计算Float平方根,类似于XNA中的Core.Sqrt

Calculate it for double and then cast back to float. 将其计算为double ,然后将其转换为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. 讨厌这样说,但0x5f3759df似乎需要3倍于Math.Sqrt。 I just did some testing with timers. 我只是对计时器进行了一些测试。 Math.Sqrt in a for-loop accessing pre-calculated arrays resulted in approx 80ms. for循环访问预先计算的数组中的Math.Sqrt导致大约80ms。 0x5f3759df under the same circumstances resulted in 180+ms 在相同情况下0x5f3759df导致180 + ms

The test was conducted several times using the Release mode optimizations. 使用Release模式优化进行了多次测试。

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();
    }
}
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM