sqrt的实现牛顿迭代法快速寻找平方根

【经典面试题】实现平方根函数sqrt

https://blog.csdn.net/xusiwei1236/article/details/25657611

实现平方根函数,不得调用其他库函数。

二分法

 //二分法
        public static float SqrtByBisection(float num) {
            if (num <= 0) return num;

            float mid;
            float low, up;
            low = 0; up = num;
            mid = (low + up) / 2;
            while (Abs(mid*mid,num)>0.01f)
            {
                if (mid * mid > num)
                {
                    up = mid;
                }
                else
                {
                    low = mid;
                }
                mid = (low + up) / 2;
            } 
            return mid;
        }

        public static float Abs(float num1,float num2 ) {
           float result = num1 - num2 ;
           return  (result >= 0) ? result : -result;
 
        }

牛顿迭代法快速寻找平方根

多数方程不存在求根公式,因此求精确根非常困难,甚至不可能,从而寻找方程的近似根就显得特别重要。方法使用函数  

泰勒级数的前面几项来寻找方程  的根。牛顿迭代法是求方程根的重要方法之一,其最大优点是在方程 

的单根附近具有平方收敛,而且该法还可以用来求方程的重根、复根,此时线性收敛,但是可通过一些方法变成超线性收敛。另外该方法广泛用于计算机编程中。

何为牛顿迭代公式

设  是 的根,选取  作为  的初始近似值,过点  做曲线  的切线  ,

  

,则  与  轴交点的横坐标  ,称  为  的一次近似值。过点

做曲线  的切线,并求该切线与x轴交点的横坐标  ,称  为r的二次近似值。重复以上过程,得  

的近似值序列,其中,  称为  的  次近似值,上式称为牛顿迭代公式

 牛顿迭代公式理论支撑:中值定理

如果函数  满足在闭区间[a,b]上连续;在开区间(a,b)内可导,那么在(a,b)内至少有一点  ,使等式

     成立。

即牛顿迭代公式中的  切线  的由来

应用到开平方中

由中值定理得 

   

假设要开根号的数为num    即:x^2=num

设方程  f(x)=x^2-num   

导数为 2*x 

  带入

得:

之后就是牛顿迭代,进入迭代,,,

代码实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sqrt开平方根的实现
{
    class Program
    {
        static void Main(string[] args)
        {
            float result01 = SqrtByNewton(64);
            Console.WriteLine(result01);

            Console.ReadKey();
        }
        //牛顿迭代法
        public static float SqrtByNewton(float num)
        {
            float val = num;

            while (Abs(val * val, num) > 0.01f)
            {
                val = (val + num / val) / 2;   
            }
            return val;
        }
        public static float Abs(float num1, float num2)
        {
            float result = num1 - num2;
            return (result >= 0) ? result : -result;

        }

    
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35422344/article/details/86479875