求平方根算法

using UnityEngine;

namespace Assets.NetSyncDemo.Test
{
    public class TestSqrt : MonoBehaviour
    {
        private void Start()
        {
            UnityEngine.Debug.Log(Sqrt(9f));

            UnityEngine.Debug.Log(Sqrt(62f));
            UnityEngine.Debug.Log(Sqrt(63f));
            UnityEngine.Debug.Log(Sqrt(64f));
            UnityEngine.Debug.Log(Sqrt(65f));
            UnityEngine.Debug.Log(Sqrt(66f));
        }

        public static float Sqrt(float x)
        {
            float result = 0f;
            float e = 0.001f;
            if (0 < x)
            {
                float low = 0;
                float high = x;
                while (low < high)
                {
                    float mid = (low + high) / 2;
                    if (mid * mid < x - e)
                    {
                        low = mid;
                    }
                    else if (mid * mid > x + e)
                    {
                        high = mid;
                    }
                    else
                    {
                        result = mid;
                        break;
                    }
                }
            }
            return result;
        }

    }
}

猜你喜欢

转载自blog.csdn.net/PangNanGua/article/details/118092496