我就廢話不多說了,大家還是直接看**吧~
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 (程式設計客棧iwww.cppcns.comnput x)
return x^2+x-6
newton (input a, input b, input e)
//a是區間下界,b是區間上界,e是精確度
x#include
#include 程式設計客棧th>
using namespace std;
double fun (double x);
double newton (double a, double b,double e);
int main()
double fun(double x)
double newton (double a, double b, double e)www.cppcns.com
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)
本文標題: python用二分法求平方根的案例
本文位址:
Python用二分法求平方根
好了,正如標題所示,我們今天要用二分法來求平方根。首先要有數字,但是老是有人寫字串該怎麼辦呢?老是有人在寫數學題的時候打字串 try x int input please enter a whole number to measure to square root except print 然後是重...
二分法求平方根(Python實現)
使用二分法 bisection method 求平方根。1 defsqrtbi x,epsilon 2assert x 0,x must be non nagtive,not str x 3assert epsilon 0,epsilon must be postive,not str epsilo...
二分法做平方根
注意這裡的浮點數 不然的話程式會報錯 coding utf 8 二分法計算20的平方根 import math a 0.0 多次二分後會變成二分法,所以要設定成浮點數,python裡就是直接賦值成浮點數 b c float raw input enter a number n 100 while t...