Python用二分法求平方根的案例
更新時間:2021年03月10日 10:18:35 作者:sharkandshark
這篇文章主要介紹了Python用二分法求平方根的案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
我就廢話不多說了,大家還是直接看代碼吧~
def sq2(x,e):
e = e #誤差范圍
low= 0
high = max(x,1.0) #處理大于0小于1的數(shù)
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)
補(bǔ)充:數(shù)值計算方法:二分法求解方程的根(偽代碼 python c/c++)
數(shù)值計算方法:
二分法求解方程的根
偽代碼
fun (input x) return x^2+x-6 newton (input a, input b, input e) //a是區(qū)間下界,b是區(qū)間上界,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)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Pycharm 設(shè)置默認(rèn)解釋器路徑和編碼格式的操作
這篇文章主要介紹了Pycharm 設(shè)置默認(rèn)解釋器路徑和編碼格式的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02
python?Pandas之DataFrame索引及選取數(shù)據(jù)
這篇文章主要介紹了python?Pandas之DataFrame索引及選取數(shù)據(jù),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-07-07
Python稀疏矩陣及參數(shù)保存代碼實現(xiàn)
這篇文章主要介紹了Python稀疏矩陣及參數(shù)保存代碼實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04
Python 用turtle實現(xiàn)用正方形畫圓的例子
今天小編就為大家分享一篇Python 用turtle實現(xiàn)用正方形畫圓的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

