Python用二分法求平方根的案例

我就廢話不多說瞭,大傢還是直接看代碼吧~

def sq2(x,e):
  e = e #誤差范圍  
  low= 0 
  high = max(x,1.0) #處理大於0小於1的數
  guess = (low + high) / 2.0
  ctr = 1
  
  while abs(guess**2 - x) > e and ctr<= 1000:
    if guess**2 < x:
      low = guess
    else:
      high = guess
      
    guess = (low + high) / 2.0
    ctr += 1
  print(guess)

補充:數值計算方法:二分法求解方程的根(偽代碼 python c/c++)

數值計算方法:

二分法求解方程的根

偽代碼

fun (input x)
 return x^2+x-6
newton (input a, input b, input e)
//a是區間下界,b是區間上界,e是精確度
 x <- (a + b) / 2
 if abs(b - 1) < e:
 return x
 else:
 if fun(a) * fun(b) < 0:
  return newton(a, x, e)
 else:
  return newton(x, b, e)

c/c++:

#include <iostream>
#include <cmath>
using namespace std; 
double fun (double x);
double newton (double a, double b,double e); 
int main()
{
 cout << newton(-5,0,0.5e-5);
 return 0;
}
 
double fun(double x)
{
 return pow(x,2)+x-6;
}
 
double newton (double a, double b, double e)
{
 double x;
 x = (a + b)/2;
 cout << x << endl;
 if ( abs(b-a) < e)
 return x;
 else
 if (fun(a)*fun(x) < 0)
  return newton(a,x,e);
 else
  return newton(x,b,e);
}

python:

def fun(x):
  return x ** 2 + x - 6
def newton(a,b,e):
  x = (a + b)/2.0
  if abs(b-a) < e:
    return x
  else:
    if fun(a) * fun(x) < 0:
      return newton(a, x, e)
    else:
      return newton(x, b, e)
print newton(-5, 0, 5e-5)

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀: