faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

6 of 8 people (75%) answered Yes
Recently 5 of 7 people (71%) answered Yes

Entry

Machine precision in Python

Jul 5th, 2000 09:59
Nathan Wallace, Hans Nowak, Snippet 51, Berthold Hoellmann


"""
Packages: maths;miscellaneous
"""

"""
For a package I'm writing I need the machine precision for python
Floats. I was unable to find a variable or function returning it, so I
wrote the attached, small module:
"""

#-------- snip eps.py ------------
# Copyright © 1999 by Berthold Höllmann, se6y095@public.uni-hamburg.de
#
# Permission to use, copy, modify, and distribute this software for
# any purpose and without fee is hereby granted.
#
# I (Berthold Höllmann) disclaim all warranties with regard to this
# software, including all implied warranties of merchantability and
# fitness, in NO EVENT shall I be liable for any special, indirect or
# consequential damages or any damages whatsoever resulting from loss
# of use, data or profits, whether in an action of contract,
# negligence or other tortious action, arising out of or in connection
# with the use or performance of this software.

"""
A small module to calculate the machine precision for the python Floats.

Usage:

    >>> import eps
    >>> print eps.eps()
    2.22044604925e-16

This eps-value is calculated on my i386 (Pentium II) Linux box.
"""

class __eps:
    def __init__(self):
        self.__eps = None
    def __call__(self):
        if not self.__eps:
            self.__eps = 1
            while (self.__eps/2. + 1.) > 1.:
                self.__eps = self.__eps / 2.
        return self.__eps

eps = __eps()

if __name__ == "__main__":
    print eps()