## 2019年2月1日金曜日

### 数学 - Python - HITCHIN' UP YOUR PYTHON WAGON - GUESSING AND CHECKING WITH CONDITIONALS - FINDING A SQUARE ROOT

Math Adventures with Python: An Illustrated Guide to Exploring Math with Code (Peter Farrell(著)、No Starch Press)のPART Ⅰ(HITCHIN' UP YOUR PYTHON WAGON)、3(GUESSING AND CHECKING WITH CONDITIONALS)、EXERCISE3-2(FINDING A SQUARE ROOT)の解答を求めてみる。

コード

Python 3

```#!/usr/bin/env python3

def average(*nums) -> float:
return sum(nums) / len(nums)

def square_root(num, low, high, epsilon=0.01):
guess = average(low, high)
square = guess ** 2
while abs(square - num) >= epsilon:
if square < num:
low = guess
else:
high = guess
guess = average(low, high)
square = guess ** 2
return guess

nums = [200, 1000, 50000]
for num in nums:
print(f'{num}: 約{square_root(num, 1, num)}')

for epsilon in [0.1, 0.01, 0.001]:
print(f'誤差: {epsilon}')
for num in nums:
print(f'{num}: 約{square_root(num, 1, num, epsilon)}')
```

```\$ python3 sample1.py
200: 約14.1419677734375
1000: 約31.622823238372803
50000: 約223.60678881779313

200: 約14.1419677734375
1000: 約31.624252319335938
50000: 約223.60697507858276

200: 約14.1419677734375
1000: 約31.622823238372803
50000: 約223.60678881779313

200: 約14.142157554626465
1000: 約31.622763693332672
50000: 約223.60679754876764
\$
```