简体   繁体   English

测量浮点精度得到N个小数位

[英]Measuring the accuracy of floating point results to N decimal places

I'm testing some implementations of Pi in python (64-bit OS) and am interested in measuring how accurate the answer is (how many decimal places were correct?) for increasing iterations. 我正在测试python(64位操作系统)中Pi的一些实现,并且我有兴趣测量答案的准确度(多少小数位是正确的?)以增加迭代次数。 I don't wish to compare more than 15 decimal places because beyond that the floating point representation itself is inaccurate. 我不希望比较超过15个小数位,因为除此之外,浮点表示本身是不准确的。

Eg for a low iteration count, the answer I got is 例如,对于低迭代计数,我得到的答案是

>>> x
3.140638056205993

I wish to compare to math.pi 我希望与math.pi进行比较

>>> math.pi
3.141592653589793

For the above I wish my answer to be 3 (3rd decimal is wrong) The way I've done it is: 对于上面我希望我的答案是3(小数点后3位错误)我做的方式是:

>>> p = str('%.51f' % math.pi)
>>> q = str('%.51f' % x)
>>> for i,(a,b) in enumerate(zip(p,q)):
...     if a != b:
...         break

The above looks clumsy to me, ie converting floats to strings and then comparing character by character, is there a better way of doing this, say more Pythonic or that uses the raw float values themselves? 上面看起来很笨拙,即将浮点数转换为字符串,然后逐个字符地进行比较,是否有更好的方法可以做到这一点,比如更多Pythonic或者使用原始浮动值本身?

Btw I found math.frexp, can this be used to do this? 顺便说一下,我发现math.frexp,这可以用来做到这一点吗?

>>> math.frexp(x)
(0.7851595140514982, 2)

You can compute the logarithm of the difference between the two 您可以计算两者之间差异的对数

>>> val = 3.140638056205993
>>> epsilon = abs(val - math.pi)
>>> abs(int(math.log(epsilon, 10))) + 1
3

Essentially, you're finding out which power of 10 does it take to equal the difference between the two numbers. 从本质上讲,你要找出等于两个数字之间差异所需的10的幂。 This only works if the difference between the two numbers is less than 1. 仅当两个数字之间的差异小于1时才有效。

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

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