2016-05-28 3 views
-1

二等分を使って平方根を求める次のコードがありますが、なんらかの理由でそれはできません。私が9の平方根を求めたいとき、私は4.5を得ます。二等分を使った平方根計算

y = float(input('Enter the number that you want to find the square root of: ')) 
z = y 
x = 0 
ans = 0 

while abs(ans**2 - abs(y)) > 0.0001 and ans <= x: 
    ans = (x + y)/2.0 

    if ans**2 < z: 
     x = ans 
    else: 
     y = ans 


print 'The square root of', z, 'is', ans 
+1

次のいずれかの回答が問題を解決する場合は、それを受け入れる必要があります(該当する回答の横にあるチェックマークをクリックしてください)。それは2つのことをします。あなたの問題があなたの満足のために解決されたことを誰にでも知らせることができます。詳しい説明は[here](http://meta.stackexchange.com/a/5235)を参照してください。 –

答えて

0

数xの平方根:sqrt=x**(1.0/2)

オルタナティブ:二等分アルゴリズムを使用して

import math 
math.sqrt(x) 

y = float(input('Enter the number that you want to find the square root of: ')) 
num = y 
x = 0 
ans = 0 

while abs(ans**2 - abs(num)) > 0.0001 and ans <= y: 
    ans = (x + y)/2.0 
    if ans**2 < num: 
     x = ans 
    else: 
     y = ans 

print 'The square root of', num, 'is', ans 
1

yがあなたであるため、あなたは、ans <= yかどうかを確認する必要がありますこの場合は右の境界になります。あなたがループ内yを変更しているので、また、あなたは、z、ないyの絶対値にans**2を比較する必要があります。Keiwanは、あなたのスクリプトで間違っていたものを説明した

while abs(ans**2 - abs(z)) > 0.00001 and ans <= y: 
    ans = (x + y)/2.0 

    if ans**2 < z: 
     x = ans 
    else: 
     y = ans 
0

が、ここで整理するわずかに異なる方法です論理。コードを読みやすくするために変数名の一部を変更しましたが、使いやすくするために関数に入れました。以下のコードは、Python 2またはPython 3で動作しますが、浮動小数点数の表示方法には若干の違いがあります。

from __future__ import print_function, division 

def sqrt_bisect(z, tol=1E-12): 
    ''' Find the square root of `z` by bisection, with tolerance `tol` ''' 
    lo, hi = 0, z 
    while True: 
     mid = (lo + hi)/2.0 
     delta = mid * mid - z 
     if abs(delta) < tol: 
      break 

     if delta > 0: 
      #Too high 
      hi = mid 
     else: 
      #Too low 
      lo = mid 

    return mid 

for z in (1, 9, 16, 200): 
    x = sqrt_bisect(z) 
    print(z, x, x*x) 

出力

1 1.0 0.999999999999 
9 3.0 9.0 
16 4.0 16.0 
200 14.1421356237 200.0 

(すなわち出力はPython 2を使用して作成されました)。

ちょうど楽しいので、ここではその機能のよりコンパクトなバリエーションです。

別のlohi変数を使用して、バイセクシングする間隔の境界を格納する代わりに、このバージョンではboundsという名前のリストを使用します。文bounds[delta > 0] = midは、Falseが数値的に0に等しく、Trueが1に等しいために機能します。したがって、deltaが正の場合、bounds[delta > 0]bounds[1]に相当します。それは巧妙なトリックですが、です。あなたがその構築に慣れていない場合は、コードを少し読みにくくしてください。

def sqrt_bisect(z, tol=1E-12): 
    ''' Find the square root of `z` by bisection, with tolerance `tol` ''' 
    bounds = [0, z] 
    while True: 
     mid = sum(bounds)/2.0 
     delta = mid * mid - z 
     if abs(delta) < tol: 
      break 
     bounds[delta > 0] = mid 

    return mid 
関連する問題