2019年3月10日日曜日

開発環境

Math Adventures with Python: An Illustrated Guide to Exploring Math with Code (Peter Farrell(著)、No Starch Press)のPART 2(RIDING INTO MATH TERRITORY)、8(USING MATRICES FOR COMPUTER GRAPHICS AND SYSTEMS OF EQUATIONS)、EXERCISE 8-1(MORE TRANSFORMATION MATRICES)の解答を求めてみる。

コード

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)}')

0 コメント:

コメントを投稿

関連コンテンツ