1

私のユースケースを示す例:

from __future__ import division
a = 215 / 4
print a # Case 1. Should print 53.75

a = 215 / 3
print a # Case 2. Should print 71.6666666666666714 i.e. decimal to 16 precision.

機能しない可能性のある解決策:

print str(a) # Case 2 gets printed with only 12 precision (needed 16)

print repr(a) # Case 2 gets printed as 71.66666666666667 (precision 14, needed 16)

print '{0:.16f}'.format(a) # Case 1 gets printed with trailing zeroes

print '{0:.16g}'.format(a) # Decimal precision is 14, needed 16.

これに対する最良のpythonicソリューションは何でしょうか?

編集: 16 の精度がfloat除算の制限である場合、小数点以下 8 桁の精度を取得する Pythonic な方法は何でしょうか。より良いソルンはありますか。よりも'{0:.8f}'.format(a).rstrip('0')

4

1 に答える 1

1

getcontext() は、10 進ライブラリーであなたの友達になると思います。

これにより、精度を設定し、有効数字の結果を操作できます。

https://docs.python.org/2/library/decimal.html

于 2015-02-23T04:32:55.537 に答える