简体   繁体   中英

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. I don't wish to compare more than 15 decimal places because beyond that the floating point representation itself is inaccurate.

Eg for a low iteration count, the answer I got is

>>> x
3.140638056205993

I wish to compare to 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:

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

Btw I found math.frexp, can this be used to do this?

>>> 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. This only works if the difference between the two numbers is less than 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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