سؤال

كيف يمكنني حساب الجذر التربيعي لـ Float في C#, ، مشابه ل Core.Sqrt في XNA؟

هل كانت مفيدة؟

المحلول

حسابه ل double ثم يلقي مرة أخرى إلى تعويم. قد تكون بطيئة بعض الشيء ، ولكن يجب أن تعمل.

(float)Math.Sqrt(inputFloat)

نصائح أخرى

أكره أن يقول هذا ، ولكن يبدو أن 0x5f3759df يستغرق 3x طالما Math.Sqrt. لقد فعلت بعض الاختبارات مع الموقتات. أدى 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();
    }
}
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 مع الإسناد
لا تنتمي إلى StackOverflow
scroll top