0
「平方根」のループに考えます妥当な値xを返し、の平方根の推定値を返します。です。このようなテーブルを表示する関数の名前test_square_root書き、それをテストするには :は、Python第2版エクササイズ7-1
a mysqrt(a) math.sqrt(a) diff
- --------- ------------ ----
1.0 1.0 1.0 0.0
2.0 1.41421356237 1.41421356237 2.22044604925e-16
3.0 1.73205080757 1.73205080757 0.0
4.0 2.0 2.0 0.0
5.0 2.2360679775 2.2360679775 0.0
6.0 2.44948974278 2.44948974278 0.0
7.0 2.64575131106 2.64575131106 0.0
8.0 2.82842712475 2.82842712475 4.4408920985e-16
9.0 3.0 3.0 0.0
は、ここで私が書いたものだ:
import math
def mysqrt(a):
x = a/5
while True:
y = (x+ a/x)/2
if y == x:
return x
x = y
def test_square_root():
a = 1.0
print('a', repr(mysqrt(a)).rjust(6), repr(math.sqrt(a)).rjust(12), 'diff'.rjust(10))
print("- --------- ------------ ----")
while a < 10.0:
print(a, " ", mysqrt(a), " ", math.sqrt(a), " ", abs(mysqrt(a)-math.sqrt(a)))
a += 1
test_square_root()
は、ここで私が得たものです:
a 1.0 1.0 diff
- --------- ------------ ----
1.0 1.0 1.0 0.0
2.0 1.414213562373095 1.4142135623730951 2.220446049250313e-16
3.0 1.7320508075688772 1.7320508075688772 0.0
4.0 2.0 2.0 0.0
5.0 2.23606797749979 2.23606797749979 0.0
6.0 2.449489742783178 2.449489742783178 0.0
7.0 2.6457513110645907 2.6457513110645907 0.0
8.0 2.82842712474619 2.8284271247461903 4.440892098500626e-16
9.0 3.0 3.0 0.0
あなたと配列がきれいに整列していないことがわかります。要素の長さが同じでない場合は、どのように配列を印刷できますか?ありがとうございました!
whileループで出力文字列をフォーマットする必要があります。 '.format()'と[format specifiers](https://pyformat.info/)を見てください。次に、固定数の場所で列を作ることができます。 – pylang