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

时间:2022-09-12 07:42:10

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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++)

数值计算方法:

二分法求解方程的根

伪代码

?
1
2
3
4
5
6
7
8
9
10
11
12
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++:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#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:

?
1
2
3
4
5
6
7
8
9
10
11
12
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)

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

原文链接:https://blog.csdn.net/sharkandshark/article/details/83625839