Python用二分法求平方根的案例
我就廢話不多說(shuō)了,大家還是直接看代碼吧~
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ù)值計(jì)算方法:二分法求解方程的根(偽代碼 python c/c++)
數(shù)值計(jì)算方法:
二分法求解方程的根偽代碼
fun (input x) return x^2+x-6newton (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 - 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)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. 詳解Android studio 動(dòng)態(tài)fragment的用法2. 編程語(yǔ)言PHP在Web開(kāi)發(fā)領(lǐng)域的優(yōu)勢(shì)在哪?3. 什么是python的自省4. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁(yè)效果(實(shí)例代碼)5. 解決Android studio xml界面無(wú)法預(yù)覽問(wèn)題6. 基于android studio的layout的xml文件的創(chuàng)建方式7. Android如何加載Base64編碼格式圖片8. Springboot Druid 自定義加密數(shù)據(jù)庫(kù)密碼的幾種方案9. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)10. 圖文詳解vue中proto文件的函數(shù)調(diào)用

網(wǎng)公網(wǎng)安備