開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
多くの言語で(?)Pythnoのround関数に相当するのはround-to-evenで四捨五入ではないから、まずPythonで本当に四捨五入な関数を定義してみた。RもPythonもround-to-evenなのでround(0.5)は0 https://t.co/7OU1Zrm8eC
— Haruhiko Okumura (@h_okumura) August 12, 2019
コード
Python 3
kmath_test.py
#!/usr/bin/env python3
from unittest import TestCase, main
from kmath import round_off
class RoundOffTest(TestCase):
def setUp(self) -> None:
pass
def tearDown(self) -> None:
pass
def test_not_even(self) -> None:
ds: [float] = [-1.6, -1.5, -1.4, -0.6, -0.5, -0.4,
0.4, 0.5, 0.6, 1.4, 1.5, 1.6]
expected: [int] = [-2, -2, -1, -1, -1, 0,
0, 1, 1, 1, 2, 2]
for a, b in zip(ds, expected):
self.assertEqual(round_off(a), b)
if __name__ == '__main__':
main()
kmath.py
#!/usr/bin/env python3
def round_off(d: float) -> int:
n: int = int(d)
decimal_part: float = d - n
if d < 0:
if decimal_part <= -0.5:
return n - 1
return n
if decimal_part < 0.5:
return n
return n + 1
入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal、Jupyter(IPython))
$ ./kmath_test.py . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK $
⚠️浮動小数点数の計算による誤差が発生する場合を考慮してない。
0 コメント:
コメントを投稿