2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python最大桁から有効数字で丸める

Last updated at Posted at 2023-08-03

Pythonである数字を有効桁数で丸めたい。

round関数を用いれば、小数点ある桁で丸められるが、今回は最大桁数から動的に丸めたい

例: 有効数字3桁
0.0012344 -> 0.00123
12344000 -> 12300000
123.44 -> 123

そのための関数を作成した。

関数本体

import math
from typing import Union
InputType = Union(float, int, list["InputType"])
def round_sigdig(val: InputType, sigdig: int) -> InputType:
    """最大桁からある桁数で丸める関数
    Args:
        val (any):
            number or list of number or array of number
            数値もしくは数値のlistもしくは数値のarray
        sigdig (int):
            significant digits
            有効桁数
    Returns:
        any: 
            number or list (same shape of val)
            丸められた数値もしくは入力と同じ形のlist
    """
    _sigdig = sigdig - 1
    def _round_sigdig(val):
        if isinstance(val, list):
            return list(map(_round_sigdig, val))
        d = int(-(math.floor(math.log10(abs(val)))-_sigdig))
        val = round(val, d)
        if val >= 10**(_sigdig):
            return int(val)
        else:
            return val
    return _round_sigdig(val)

使用例

print(1/7, round_sigdig(1/7, 5))
# 0.14285714285714285 0.14286

こちらの関数はlistに対応している。

array = [0.1, 1/3, math.sqrt(2), 120.3333, 99990000, 239200000, 0.0000000001234, 3, 45.000000000123]

print(array)
print(round_sigdig(array, 3))
# [0.1, 0.3333333333333333, 1.4142135623730951, 120.3333, 99990000, 239200000, 1.234e-10, 3, 45.000000000123]
# [0.1, 0.333, 1.41, 120, 100000000, 239000000, 1.23e-10, 3, 45.0]

もちろん多次元配列でも対応可能

array2 = [
    [0.1, 1/3, math.sqrt(2)],
    [120.3333, 99990000, 239200000],
    [0.0000000001234, 3, 45.000000000123]
]

print(array2)
print(round_sigdig(array2, 5))
# [[0.1, 0.3333333333333333, 1.4142135623730951], [120.3333, 99990000, 239200000], [1.234e-10, 3, 45.000000000123]]
# [[0.1, 0.33333, 1.4142], [120.33, 99990000, 239200000], [1.234e-10, 3, 45.0]]

注意点

有効桁数で丸めたときに整数になる場合はint型にキャスティングしている。
あくまでround関数なので、必ずしも四捨五入ではないことに注意

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?