【问题标题】:Handling high precision decimals处理高精度小数
【发布时间】:2018-03-13 16:37:49
【问题描述】:

我对 python 很陌生,我必须执行 python 代码的唯一原因是 JavaScript 的 32 位数字的限制。

情况:
我必须计算以下最大比例 38 和 19 个小数位的精度。 [MSSQL Ref: DECIMAL(38,19)]

数学运算: ((39.992 * 0.0000467788) * 0.02 / 100)

代码:

from decimal import *
import math

def truncate(f, n):
    '''Truncates/pads a float f to n decimal places without rounding'''
    s = '{}'.format(f)
    if 'e' in s or 'E' in s:
        return '{0:.{1}f}'.format(f, n)
    i, p, d = s.partition('.')
    return '.'.join([i, (d+'0'*n)[:n]])

getcontext().prec = 28

expectedTotal = "0.0000003741555539199"

vol = Decimal(39.992)
rate = Decimal(0.0000467788)
percent = Decimal(0.02)

cal1 = Decimal(truncate(((vol) * rate * percent),19))
print("(vol * rate * percent) at 19 decimal places: {}".format(cal1))

total = Decimal((vol * rate) * percent / 100)
print("total that I get: {}".format(total))
print("total that I want: {}".format(expectedTotal))

结果:

(vol * rate * percent) at 19 decimal places: 0.0000374155553919999
total that I get: 3.74155553919999983602300172E-7
total that I want: 0.0000003741555539199

积分:
1. 精度超过小数点后 19 位我没用。
2. truncate 函数SO Link 将值转换为字符串并截断。
3. 我尝试截断到小数点后 17 位,然后除以 100,但没有成功。

【问题讨论】:

  • "vol = Decimal(39.992)" 你已经输了。 vol = Decimal('39.992')

标签: python python-2.7 decimal


【解决方案1】:

您可以在 Python 中取消科学记数法:

x = 3.74155553919999983602300172E-7
print('{:f}'.format(x))
>> 0.000000
print('{:.20f}'.format(x))
>> 0.00000037415555392000

请注意,默认精度为 6,但在示例情况下还不够,因此您可以像我在第二个测试中所做的那样表达您的精度。

注意:如果你设置了一个特定的数字,Python 会在需要时在末尾填充零。

【讨论】:

  • 这正是我刚刚所做的。正如我坐在我旁边的朋友@nigharsh 所建议的那样:D,谢谢,这是我猜的唯一方法
猜你喜欢
  • 1970-01-01
  • 2012-07-20
  • 1970-01-01
  • 2016-03-07
  • 2011-01-11
  • 1970-01-01
  • 2021-12-18
  • 2017-11-01
  • 1970-01-01
相关资源
最近更新 更多