Python’s case of finding the square root by dichotomy

Time:2021-10-15

I’ll stop talking nonsense. Let’s look at the code directly~

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def sq2(x,e):
  e = E error range
  low= 0
  high = max(x,1.0)Treatment greater than0less than1Number of
  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)

Supplement: numerical calculation method: dichotomy to solve the root of the equation (pseudo code Python C / C + +)

Numerical calculation method:

Root of equation solved by dichotomy

Pseudo code

?
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 is the lower bound of the interval, B is the upper bound of the interval, and E is the accuracy
 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)

The above is my personal experience. I hope I can give you a reference, and I hope you can support developepper. If you have any mistakes or don’t consider completely, please don’t hesitate to comment.