您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:Python用二分法求平方根的案例

51自学网 2021-10-30 22:49:46
  python
这篇教程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-6newton (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 - 6def 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)

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


Python读取GSMap数据的问题
Python入门基础之import机制
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。