简体   繁体   English

处理高精度小数

[英]Handling high precision decimals

I am pretty new to python and the only reason i have to execute a python code is because of the limitations of JavaScript's 32 bit numbers. 我是python的新手,我必须执行python代码的唯一原因是因为JavaScript的32位数字的限制。

Situation: 情况:
I have to calculate the following to a max scale of 38 and precision of 19 Decimal Places. 我必须计算以下内容,最大比例为38,精度为19个小数位。 [MSSQL Ref: DECIMAL(38,19)]

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

Code: 码:

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

Result: 结果:

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

Points: 要点:
1. I have no use for accuracy beyond 19 decimal places. 1.精度超过19位小数我没有用。
2. truncate function SO Link converts value to string and truncates. 2.截断函数SO Link将值转换为字符串并截断。
3. I tried truncating to 17 decimal places then dividing by 100, but didnt work. 3.我尝试截断到小数点后17位,然后除以100,但是没有用。

You can supress the scientific notation in Python: 您可以禁止使用Python中的科学符号:

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

Note that the default precision is 6 however in the example case is not enough so you can express your precision like I did in the second test. 请注意,默认精度为6,但是在示例情况下还不够,因此您可以像在第二个测试中一样来表达您的精度。

NB: that if you set a specific number Python is going to fill in with zeros at the end if needed. 注意:如果您设置一个特定的数字,Python将在需要时在末尾填充零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM