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

来自:互联网
时间:2021-03-10
阅读:

我就废话不多说了,大家还是直接看代码吧~

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)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

返回顶部
顶部