如何将pythons Decimal()类型转换为INT和exponen

2024-10-01 15:32:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python中使用Decimal()数据类型,并将其转换为整数和指数,这样我就可以将这些数据发送到具有完全精度和十进制控制的微控制器/plc。https://docs.python.org/2/library/decimal.html

我已经让它工作了,但它太粗糙了,有人知道更好的方法吗?如果不是的话,我会选择哪种方式来编写一个较低级别的“as_int()”函数?在

示例代码:

from decimal import *
d=Decimal('3.14159')
t=d.as_tuple()
if t[0] == 0:
    sign=1
else:
    sign=-1

digits= t[1]
theExponent=t[2]
theInteger=sign * int(''.join(map(str,digits)))

theExponent
theInteger

对于那些没有编程的plc,我的替代方法是在两个系统中使用int并声明小数点,或者使用浮点(只有一些plc支持)并且是有损的。所以你就能明白为什么能做到这一点会很棒!在

提前谢谢!在


Tags: 数据方法as精度整数指数intplc
3条回答

你可以这样做:

[这比其他方法快3倍]

d=Decimal('3.14159')

list_d = str(d).split('.')   
# Converting the decimal to string and splitting it at the decimal point

# If decimal point exists => Negative exponent
# i.e   3.14159 => "3", "14159"
# exponent = -len("14159") = -5
# integer = int("3"+"14159") = 314159

if len(list_d) == 2:
    # Exponent is the negative of length of no of digits after decimal point
    exponent = -len(list_d[1])
    integer = int(list_d[0] + list_d[1])



# If the decimal point does not exist => Positive / Zero exponent
# 3400
# exponent = len("3400") - len("34") = 2
# integer = int("34") = 34

else:
    str_dec = list_d[0].rstrip('0')
    exponent = len(list_d[0]) - len(str_dec)
    integer = int(str_dec)

print integer, exponent

性能测试

^{pr2}$ 计算两种方法100000次循环所需的时间:
ttaken = time.time()
for i in range(100000):
    d = Decimal(random.uniform(-3, +3))
    to_int_exp(d)    
ttaken = time.time() - ttaken
print ttaken

字符串分析方法所用时间:1.56606507301

ttaken = time.time()
for i in range(100000):
    d = Decimal(random.uniform(-3, +3))
    to_int_exp1(d)    
ttaken = time.time() - ttaken
print ttaken

转换为元组然后提取方法所用的时间:4.67159295082

from functools import reduce   # Only in Python 3, omit this in Python 2.x
from decimal import *

d = Decimal('3.14159')
t = d.as_tuple()

theInteger = reduce(lambda rst, x: rst * 10 + x, t.digits)
theExponent = t.exponent

直接从元组中获取指数:

exponent = d.as_tuple()[2]

然后乘以10的适当幂:

^{pr2}$

综合起来:

from decimal import Decimal

_ten = Decimal('10')

def int_exponent(d):
    exponent = d.as_tuple()[2]
    int_part = int(d * (_ten ** -exponent))
    return int_part, exponent

相关问题 更多 >

    热门问题