Python用二分法求平方根的案例
作者:sharkandshark 时间:2021-09-27 10:05:01
我就废话不多说了,大家还是直接看代码吧~
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)
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。
来源:https://blog.csdn.net/sharkandshark/article/details/83625839
标签:Python,二分法,平方根
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
asp里Sub与Function有什么区别
2007-08-17 10:39:00
CSS Shadow Practice
2009-04-01 18:37:00
python实现蒙特卡罗模拟法的实践
2023-08-11 02:22:02
![](https://img.aspxhome.com/file/2023/1/62271_0s.png)
Python创建文件和追加文件内容实例
2021-03-15 04:38:09
Django实现简单网页弹出警告代码
2022-12-31 06:56:16
Python代码缩进和测试模块示例详解
2021-08-31 06:49:10
一组常用的弹出窗口用法总结
2007-10-08 13:04:00
pandas DataFrame实现几列数据合并成为新的一列方法
2021-05-22 01:36:00
![](https://img.aspxhome.com/file/2023/3/92163_0s.jpg)
python opencv图像处理(素描、怀旧、光照、流年、滤镜 原理及实现)
2021-11-30 22:35:03
![](https://img.aspxhome.com/file/2023/0/91840_0s.png)
10个简化PHP开发的工具
2023-07-14 18:02:05
![](https://img.aspxhome.com/file/2023/3/55293_0s.png)
日期垂直排列的两种技巧
2009-08-28 12:38:00
![](https://img.aspxhome.com/file/UploadPic/20098/28/01-16s.jpg)
SQL Server查询速度慢的原因及优化方法
2009-01-05 13:46:00
python-字典dict和集合set
2021-09-30 10:10:17
图片垂直居中的使用技巧
2008-05-28 12:45:00
zen coding的dreamweaver插件安装教程
2010-01-12 13:30:00
![](https://img.aspxhome.com/file/UploadPic/20101/12/zencoding-13s.jpg)
python基础入门之列表(一)
2023-11-23 19:33:42
![](https://img.aspxhome.com/file/2023/9/97249_0s.png)
Python深度学习之Pytorch初步使用
2023-08-12 08:16:41
![](https://img.aspxhome.com/file/2023/5/68895_0s.png)
Python中三种时间格式转换的方法
2023-10-18 13:11:43
![](https://img.aspxhome.com/file/2023/2/100932_0s.png)
asp如何处理页面执行时发生的错误?
2009-11-14 20:43:00
Dreamweaver使用技巧之如何巧用DW4文件库更新网站
2010-10-20 20:07:00
![](https://img.aspxhome.com/file/UploadPic/20072/20072311301764s.gif)