[英]High precision arithmetric in Python and/or C/C++?
摘要:對於非常高精度的算術運算,哪種Python軟件包或C-Library是最佳選擇?
我有一些函數可以將小數日( 0.0-0.99999..
)轉換為人類0.0-0.99999..
格式(小時,分鍾,秒;但更重要的是:毫秒,微秒,納秒)。
轉換是通過以下功能完成的:(請注意,我尚未實現時區校正)
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
我的來回轉換結果不准確,但是:
jdatetime.DayTime.fromfractional(d(0.567784356873)).to_fractional()
Decimal('0.56779150214342592592592592592592592592592592592592592592592592592592592592592592592592592592592592592592592592592')
# Difference in-out: Decimal('0.000007145270')
當我更改d()
以返回常規Python浮點數時:
# Difference in-out: 7.1452704258900823e-06 (same)
因此,我的問題是:哪個Python軟件包或C庫能夠更准確地做到這一點?
差異是由於您的代碼中的錯誤,而不是由於任何准確性問題引起的。 線
output += self.nanosecond * (d(8.64) * d(10)**d(-9))
應該是這樣的
output += self.nanosecond / d(86400000000000)
此外,在代碼中使用浮點文字並將其轉換為Decimal
是一個壞主意。 這將首先將文字數字四舍五入到浮點精度。 后來轉換為Decimal
不能恢復丟失的精度。 嘗試
d = decimal.Decimal
並僅使用整數文字(只需刪除.0
部分)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.