Math Adventures with Python
An Illustrated Guide to Exploring Math with Code
楽天ブックス(Kobo)
紀伊国屋書店(Kinoppy)
開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
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)}')
入出力結果(cmd(コマンドプロンプト)、Terminal、Jupyter(IPython))
$ python3 sample1.py 200: 約14.1419677734375 1000: 約31.622823238372803 50000: 約223.60678881779313 誤差: 0.1 200: 約14.1419677734375 1000: 約31.624252319335938 50000: 約223.60697507858276 誤差: 0.01 200: 約14.1419677734375 1000: 約31.622823238372803 50000: 約223.60678881779313 誤差: 0.001 200: 約14.142157554626465 1000: 約31.622763693332672 50000: 約223.60679754876764 $
0 コメント:
コメントを投稿