0
0

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.

誤差なし正整数除算をする関数

Posted at

Decimalを使えば良いのですが、練習のために自分で関数を書いてみました。
筆算と同じことをすれば良いです。
関数g(a,b,n)を定義し、aをbで割った値を、小数点以下n桁まで計算してstrで返すようにします。四捨五入はせず、n+1桁目以降は切り捨てられます。
以下python3での実装です。

def g(a, b, n):
    def f(a, b, n):
        if n == 0 or a == 0: return ""
        else: return str(a * 10 // b) + f(a * 10 % b, b, n - 1)
    assert a >= 0 and b > 0 and n >= 0
    period = "." if a % b != 0 else ""
    return str(a // b) + period + f(a % b, b, n)

print(g(1,1024,5))   # 0.00097
print(g(1,1024,10))  # 0.0009765625

fが小数点以下部分、gが整数部分の計算をします。
関数fのor a == 0を除けば、途中で割り切れる場合も小数点以下n桁目まで0で埋められます。

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?