高precision arithmetric在Python和/或C / C ++? [英] High precision arithmetric in Python and/or C/C++?
问题描述
摘要:哪一种Python包或C-图书馆是非常高的precision算术运算的最佳选择
我有一些功能,这转换分数天( 0.0-0.99999 ..
),以一个人readible格式(小时,分,秒;但更重要的是:毫秒,微秒,纳秒级)。
I have some functions which convert fractional days (0.0-0.99999..
) to a human-readible format (hours, minutes, seconds; but more importantly: milliseconds, microsecond, nanoseconds).
转换是通过这些功能来完成:
(请注意,我还没有实现时区校正尚)
Conversion is done by these functions: (note that I haven't implemented timezone correction yet)
d = lambda x: decimal.Decimal(str(x))
cdef object fractional2hms(double fractional, double timezone):
cdef object total, hms, ms_mult
cdef int i
hms = [0,0,0,0,0,0]
ms_mult = (d(3600000000000), d(60000000000), d(1000000000), d(1000000), d(1000), d(1))
# hms = [0,0,0,0,0]
total = d(fractional) * d(86400000000000)
for i in range(len(ms_mult)):
hms[i] = (total - (total % ms_mult[i])) / ms_mult[i]
total = d(total % ms_mult[i])
return ([int(x) for x in hms])
和以分数:
def to_fractional(self):
output = (self.hour / d(24.0)) + (self.minute / d(1440.0))
output += (self.second / d(86400.0)) + (self.millisecond / d(86400000.0))
output += self.microsecond / d(86400000000.0)
output += self.nanosecond * (d(8.64) * d(10)**d(-9))
return output
我的背,来回转换的结果是不准确的,但是:
My results of a back-and-forth conversion are inaccurate, however:
jdatetime.DayTime.fromfractional(d(0.567784356873)).to_fractional()
Decimal('0.56779150214342592592592592592592592592592592592592592592592592592592592592592592592592592592592592592592592592592')
# Difference in-out: Decimal('0.000007145270')
在更改 D()
返回一个常规的Python浮动:
When I change d()
to return a regular Python float:
# Difference in-out: 7.1452704258900823e-06 (same)
我的问题因此:哪一种Python包或C-库能够做到这一点更精确地
My question is therefore: Which Python package or C-library is able to do this more accurately?
推荐答案
的差异是由于存在错误,在code,不会因任何准确性问题。行
The difference is due to a bug in your code, not due to any accuracy issue. The line
output += self.nanosecond * (d(8.64) * d(10)**d(-9))
应该是这样
output += self.nanosecond / d(86400000000000)
此外,它是使用浮点文字在code并将其转换为小数
一个坏主意。这将第一轮的字面数浮点精度。后来转化为小数
无法挽回失去的准确性。尝试
Furthermore, it is a Bad Idea to use floating point literals in your code and convert them to Decimal
. This will first round the literal number to floating point accuracy. The later conversion to Decimal
can't restore the lost accuracy. Try
d = decimal.Decimal
和只使用整数文本(只删除 .0
部分)。
and use only integer literals (just remove the .0
part).
这篇关于高precision arithmetric在Python和/或C / C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!