替代开方运算sqrt

8位mcu 开方 math.h  容易超ROM空间;

下面几种替代方案:二分法逐次逼近,牛顿法,

#define   sqrt    sqrt_16//sqrt0// sqrt1// sqrt2

float fsqrt(double number)
{   //牛顿叠代
    double   approx = number/2.0  ;
    double precision=0.001f;//1E-7;
     while (abs(approx * approx - number) > precision)
         approx = (approx + number / approx) / 2.0;
        return  approx;
}
uint16_t  sqrt_16(uint32_t M)
{      //整数开方 >牛顿叠代        POW(N,2)==M          N=M^0.5;   
#if  1
   // return sqrt0(M);

  1. unsigned long rem = 0;

  2. unsigned long root = 0;

  3. unsigned long divisor = 0;

  4. for(int i=0; i<16; i++){

  5. root <<= 1;

  6. rem = ((rem << 2) + (a >> 30));

  7. a <<= 2;

  8. divisor = (root<<1) + 1;

  9. if(divisor <= rem){

  10. rem -= divisor;

  11. root++;

  12. }

  13. }

  14. return root;//(unsigned short)(root);

  15. }

#else
      uint32_t i;
      uint32_t N=0;
      unsigned long tmp,ttp;
      if(M==0) 
            return 0;
      N=0;
      tmp=M>>30;//        
      M<<=2;
        if(tmp>1) 
        { 
            N++;
      

你可能感兴趣的:(算法,c语言,stm32,c#)