Floating point bug?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Terry Reedy

    #121
    Re: How about adding rational fraction to Python?


    "Arnaud Delobelle" <arnodel@google mail.comwrote in message
    news:ea3aecb0-c946-46be-bcd5-0c7584751e4b@b1 g2000hsg.google groups.com...
    | Perhaps it'll be like when I quit smoking six years ago. I didn't
    | enjoy it although I knew it was good for me... And now I don't regret
    | it even though I still have the occasional craving.

    In following the development of Py3, there have been a few decisions that I
    wish had gone otherwise. But I agree with more than the majority and am
    not going to deprive myself of what I expect to be an improved experience
    without giving Py3 a fair trial.

    tjr



    Comment

    • Anand Patil

      #122
      Re: How about adding rational fraction to Python?

      Not sure if this is common knowledge yet but Sympy,
      http://code.google.com/p/sympy, has a rational type.

      In [2]: from sympy import *

      In [3]: Rational(21,4)
      Out[3]: 21/4

      In [4]: Rational(21,4)+ Rational(3,4)
      Out[4]: 6

      Comment

      • Lie

        #123
        Re: How about adding rational fraction to Python?

        On Feb 29, 5:33 am, Steven D'Aprano <st...@REMOVE-THIS-
        cybersource.com .auwrote:
        And rightly rejected by many other programming languages, including
        modern Python, not to mention calculators, real mathematics and
        common sense.
        >
        Lost me again.  I was not aware that calculators, real mathematics
        and common sense were programming languages.
        >
        I didn't say they were. Please parse my sentence again.
        In the widest sense of the term computer and programming language,
        actually calculators and real mathematics are programming languages.
        Programming languages is a way to communicate problems with computer.
        Computer is anything that does computation (and that includes
        calculator and a room full of a bunch of people doing calculation with
        pencil and paper[1]). The expressions we write in a calculator is a
        (very limited) programming language, while mathematics conventions is
        a language to communicate a mathematician's problems with the
        computers[2] and other mathematicians

        [1] Actually the term computer was first used to refer to this bunch
        of people
        [2] The computers in this sense is people that does computation

        Comment

        • Paul Rubin

          #124
          Re: How about adding rational fraction to Python?

          Steven D'Aprano <steve@REMOVE-THIS-cybersource.com .auwrites:
          def mean(data): return sum(data)/len(data)
          >
          That does the right thing for data, no matter of what it consists of:
          floats, ints, Decimals, rationals, complex numbers, or a mix of all of
          the above.
          One of those types is not like the others: for all of them except int,
          the quotient operation actually is the inverse of multiplication.
          So I'm unpersuaded that the "mean" operation above does the "right
          thing" for ints. If the integers being averaged were prices
          in dollars, maybe the result type should even be decimal.

          For this reason I think // is a good thing and I've gotten accustomed
          to using it for integer division. I can live with int/int=float but
          find it sloppy and would be happier if int/int always threw an error
          (convert explicitly if you want a particular type result).

          Comment

          • Paul Rubin

            #125
            Re: How about adding rational fraction to Python?

            Lie <Lie.1296@gmail .comwrites:
            That's quite complex and restrictive, but probably it's because my
            mind is not tuned to Haskell yet.
            That aspect is pretty straightforward , other parts like only being
            able to do i/o in functions having a special type are much more confusing.
            Anyway, I don't think Python should
            work that way, because Python have a plan for numerical integration
            which would unify all numerical types into an apparent single type,
            which requires removal of operator's limitations.
            Well I think the idea is to have a hierarchy of nested numeric types,
            not a single type.
            from __future import division
            a = 10
            b = 5
            c = a / b
            if c * b == a: print 'multiplication is inverse of division'
            Try with a=7, b=25

            Comment

            • Lie

              #126
              Re: How about adding rational fraction to Python?

              On Mar 2, 10:02 pm, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
              Lie <Lie.1...@gmail .comwrites:
              Anyway, I don't think Python should
              work that way, because Python have a plan for numerical integration
              which would unify all numerical types into an apparent single type,
              which requires removal of operator's limitations.
              >
              Well I think the idea is to have a hierarchy of nested numeric types,
              not a single type.
              You hit the right note, but what I meant is the numeric type
              unification would make it _appear_ to consist of a single numeric type
              (yeah, I know it isn't actually, but what appears from outside isn't
              always what's inside).
              from __future import division
              a = 10
              b = 5
              c = a / b
              if c * b == a: print 'multiplication is inverse of division'
              >
              Try with a=7, b=25
              They should still compare true, but they don't. The reason why they
              don't is because of float's finite precision, which is not exactly
              what we're talking here since it doesn't change the fact that
              multiplication and division are inverse of each other. One way to
              handle this situation is to do an epsilon aware comparison (as should
              be done with any comparison involving floats), but I don't do it cause
              my intention is to clarify the real problem that multiplication is
              indeed inverse of division and I want to avoid obscuring that with the
              epsilon comparison.

              Comment

              • Paul Rubin

                #127
                Re: How about adding rational fraction to Python?

                Lie <Lie.1296@gmail .comwrites:
                You hit the right note, but what I meant is the numeric type
                unification would make it _appear_ to consist of a single numeric type
                (yeah, I know it isn't actually, but what appears from outside isn't
                always what's inside).
                That is clearly not intended; floats and decimals and integers are
                really different from each other and Python has to treat them distinctly.
                Try with a=7, b=25
                >
                They should still compare true, but they don't. The reason why they
                don't is because of float's finite precision, which is not exactly
                what we're talking here since it doesn't change the fact that
                multiplication and division are inverse of each other.
                What? Obviously they are not exact inverses for floats, as that test
                shows. They would be inverses for mathematical reals or rationals,
                but Python does not have those.
                One way to handle this situation is to do an epsilon aware
                comparison (as should be done with any comparison involving floats),
                but I don't do it cause my intention is to clarify the real problem
                that multiplication is indeed inverse of division and I want to
                avoid obscuring that with the epsilon comparison.
                I think you are a bit confused. That epsilon aware comparison thing
                acknowledges that floats only approximate the behavior of mathematical
                reals. When we do float arithmetic, we accept that "equal" often
                really only means "approximat ely equal". But when we do integer
                arithmetic, we do not expect or accept equality as being approximate.
                Integer equality means equal, not approximately equal. That is why
                int and float arithmetic cannot work the same way.

                Comment

                • Jeff Schwab

                  #128
                  Re: How about adding rational fraction to Python?

                  Paul Rubin wrote:
                  I can live with int/int=float but
                  find it sloppy and would be happier if int/int always threw an error
                  (convert explicitly if you want a particular type result).
                  Better yet, how hard would it be to define an otherwise int-like type
                  that did not define a non-flooring division operator? Are there any
                  real use cases for such a type? Maybe a division operator could be
                  defined to perform a run-time check that, for an operation n/d==q,
                  n==q*d; else, throw an exception. Code written to support duck-typed
                  integers should work with such a UDT "out of the box."

                  Comment

                  • Mensanator

                    #129
                    sympy: nifty, but... (was: How about adding rational fraction toPython?)

                    On Mar 1, 12:29 pm, "Anand Patil" <anand.prabhaka r.pa...@gmail.c om>
                    wrote:
                    Not sure if this is common knowledge yet but Sympy,http://code.google.com/p/sympy, has a rational type.
                    I hadn't heard of this before, thanks for the link.

                    Very nifty, lots of goodies not found in gmpy (although
                    it seems to lack a modular inverse function and the linear
                    congruence solver that can be derived from it making it
                    of no value to me).

                    Alas, it's written in Python. Who writes a math library
                    in Python?

                    Nevertheless, I thought I would try out the Rational numbers.

                    Once I figured out how to use them, I converted my Polynomial
                    Finder by Newton's Forward Difference Method program to use
                    sympy instead of gmpy.

                    I have a test case where I create 1 66 degree polynomial where
                    the coefficients are large rationals. The polynomial was
                    calculated flawlessly

                    <partial output>
                    ## sympy
                    ## Term0: [66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66,
                    -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66,
                    66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66,
                    -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, -66,
                    66, -66, 66, -66, 66, -66, 66, -66, 66, -66, 66, 0]
                    ##
                    ## Seq: [66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 66]
                    ##
                    ## The Polynomial:
                    ##
                    ##
                    ## 1
                    ##
                    -------------------------------------------------------------------------------------------
                    * n**66
                    ##
                    824765059208247 066672317030678 549625218625855 134543749292212 313438895577497 600000000000000 0
                    ##
                    ##
                    ## -67
                    ##
                    ------------------------------------------------------------------------------------------
                    * n**65
                    ##
                    249928805820680 929294641524448 045340975341168 222589014937034 034375422902272 000000000000000
                    ##
                    ##
                    ## 67
                    ##
                    ---------------------------------------------------------------------------------------
                    * n**64
                    ##
                    230703513065243 934733515253336 657237823391847 590082167634185 262500390371328 000000000000

                    But because they are calculated using Python,
                    it took 175 seconds compared to 0.2 seconds
                    for gmpy to do the same polynomial.

                    So, I'll keep it around for it's neat features
                    that gmpy doesn't have, but it won't replace gmpy
                    for any serious work.

                    >
                    In [2]: from sympy import *
                    >
                    In [3]: Rational(21,4)
                    Out[3]: 21/4
                    >
                    In [4]: Rational(21,4)+ Rational(3,4)
                    Out[4]: 6

                    Comment

                    • Arnaud Delobelle

                      #130
                      Re: How about adding rational fraction to Python?

                      On Mar 3, 4:39 pm, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
                      [...]
                      You are right, C is even worse than I remembered.
                      It's good enough to be the language used for the reference
                      implementation of python :-)

                      [...]
                      --
                      Arnaud

                      Comment

                      • Lie

                        #131
                        Re: How about adding rational fraction to Python?

                        On Mar 2, 11:36 pm, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
                        Lie <Lie.1...@gmail .comwrites:
                        You hit the right note, but what I meant is the numeric type
                        unification would make it _appear_ to consist of a single numeric type
                        (yeah, I know it isn't actually, but what appears from outside isn't
                        always what's inside).
                        >
                        That is clearly not intended; floats and decimals and integers are
                        really different from each other and Python has to treat them distinctly.
                        In certain operations it would, such as:
                        a = Decimal('32.324 ')
                        b = 90.3453
                        c = 43
                        d = a + b + c <<< this should work without manual type casting

                        This behavior is what is intended in numeric type unification, floats
                        and decimals and integers should work together flawlessly without the
                        need for manual type casting. This gives the _impression_ of a single
                        numeric type (although programmers should still be aware that the
                        underlying type still exists). It's true Python have to treat them
                        differently, but programmers would be able to treat them all the same
                        (at least in most parts)
                        Try with a=7, b=25
                        >
                        They should still compare true, but they don't. The reason why they
                        don't is because of float's finite precision, which is not exactly
                        what we're talking here since it doesn't change the fact that
                        multiplication and division are inverse of each other.
                        >
                        What?  Obviously they are not exact inverses for floats, as that test
                        shows.  They would be inverses for mathematical reals or rationals,
                        but Python does not have those.
                        When I said multiplication and division are inverse, I was pointing
                        out the fact that even though float's inexactness make them imperfect
                        inverse, mult & div are still inverse of each other. In-practice, the
                        inversing behavior is impossible unless we have a way to represent
                        real number (which we don't), and the *workaround* to make them work
                        is to do epsilon comparison.

                        When I'm talking about things I usually talk in purely theoretical
                        condition first and considers practical implementations that doesn't
                        work that way as making up a workaround inside their limitations. In
                        this case, the theoretical condition is that multiplication and
                        division is inverse of each other. The practical consideration is
                        float is inexact and reals is impossible, and thus epsilon comparison
                        is necessary to walk around float's limitations so multiplication and
                        division could still be inverses.

                        Aside: Python would have rationals
                        One way to handle this situation is to do an epsilon aware
                        comparison (as should be done with any comparison involving floats),
                        but I don't do it cause my intention is to clarify the real problem
                        that multiplication is indeed inverse of division and I want to
                        avoid obscuring that with the epsilon comparison.
                        >
                        I think you are a bit confused.  That epsilon aware comparison thing
                        acknowledges that floats only approximate the behavior of mathematical
                        reals.  
                        Yes, I realized that floats aren't the same as reals.
                        When we do float arithmetic, we accept that "equal" often
                        really only means "approximat ely equal".  But when we do integer
                        arithmetic, we do not expect or accept equality as being approximate.
                        Integer equality means equal, not approximately equal.  That is why
                        int and float arithmetic cannot work the same way.
                        No, no, they don't work the same way, but they should appear to work
                        the same way as reals in pure mathematics do. Again, I'm talking in
                        theory first: ints and floats should work the same way, but since
                        practical considerations make them impossible, then they should at
                        least appear to work the same way (or they would have become
                        completely different things, remember duck typing?).

                        Comment

                        • NickC

                          #132
                          Re: How about adding rational fraction to Python?

                          On Mar 4, 7:11 am, Lie <Lie.1...@gmail .comwrote:
                          On Mar 2, 11:36 pm, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
                          Try with a=7, b=25
                          >
                          They should still compare true, but they don't. The reason why they
                          don't is because of float's finite precision, which is not exactly
                          what we're talking here since it doesn't change the fact that
                          multiplication and division are inverse of each other.
                          >
                          What? Obviously they are not exact inverses for floats, as that test
                          shows. They would be inverses for mathematical reals or rationals,
                          but Python does not have those.
                          >
                          When I said multiplication and division are inverse, I was pointing
                          out the fact that even though float's inexactness make them imperfect
                          inverse, mult & div are still inverse of each other. In-practice, the
                          inversing behavior is impossible unless we have a way to represent
                          real number (which we don't), and the *workaround* to make them work
                          is to do epsilon comparison.
                          A mildly interesting Py3k experiment:

                          Python 3.0a3+ (py3k:61229, Mar 4 2008, 21:38:15)
                          [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
                          Type "help", "copyright" , "credits" or "license" for more information.
                          >>from fractions import Fraction
                          >>from decimal import Decimal
                          >>def check_accuracy( num_type, max_val=1000):
                          .... wrong = 0
                          .... for x in range(1, max_val):
                          .... for y in range(1, max_val):
                          .... wrong += (x / num_type(y)) * y != x
                          .... return wrong
                          ....
                          >>check_accurac y(float)
                          101502
                          >>check_accurac y(Decimal)
                          310013
                          >>check_accurac y(Fraction)
                          0


                          The conclusions I came to based on running that experiment are:
                          - Decimal actually appears to suffer more rounding problems than float
                          for rational arithmetic
                          - Decimal appears to be significantly slower than Fraction for small
                          denominator rational arithmetic
                          - both Decimal and Fraction are significantly slower than builtin
                          floats

                          The increased number of inaccurate answers with Decimal (31% vs 10%)
                          is probably due to the fact that it is actually more precise than
                          float - for the builtin floats, the rounding error in the division
                          step may be cancelled out by a further rounding error in the
                          multiplication step (this can be seen happening in the case of ((1 /
                          3.0) * 3) == 1.0, where the result of the multiplication ends up being
                          1.0 despite the rounding error on division, due to the next smallest
                          floating value being 0.9999999999999 9989).

                          The speed difference between Decimal and Fraction is likely due to the
                          fact that Fraction can avoid actually doing any division most of the
                          time - it does addition and multiplication instead. The main reason
                          behind the overall speed advantage of builtin floats should hopefully
                          be obvious ;)

                          Regardless, the result of integer division is going to be a binary
                          floating point value in Py3k. For cases where that isn't adequate or
                          acceptable, the application should really be tightly controlling its
                          numeric types anyway and probably using a high performance math
                          library like numpy or gmpy instead of the standard numeric types (as
                          others have already noted in this thread).


                          Comment

                          • Mark Dickinson

                            #133
                            Re: How about adding rational fraction to Python?

                            On Mar 4, 8:46 am, NickC <ncogh...@gmail .comwrote:
                            The increased number of inaccurate answers with Decimal (31% vs 10%)
                            is probably due to the fact that it is actually more precise than
                            float
                            I suspect it has more to do with the fact that 10 is bigger than 2,
                            though I'm not sure I could precisely articulate the reasons why
                            this matters. (A bigger base means a bigger 'wobble', the wobble
                            being the variation in the relationship between an error of 1ulp and
                            a relative error of base**-precision.)

                            Rerunning your example after a

                            getcontext().pr ec = 16

                            (i.e. with precision comparable to that of float) gives
                            >>check_accurac y(Decimal)
                            310176

                            Mark

                            Comment

                            • Gabriel Genellina

                              #134
                              Re: How about adding rational fraction to Python?

                              En Tue, 04 Mar 2008 11:46:48 -0200, NickC <ncoghlan@gmail .comescribi�:
                              A mildly interesting Py3k experiment:
                              >
                              Python 3.0a3+ (py3k:61229, Mar 4 2008, 21:38:15)
                              [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
                              Type "help", "copyright" , "credits" or "license" for more information.
                              >>>from fractions import Fraction
                              >>>from decimal import Decimal
                              >>>def check_accuracy( num_type, max_val=1000):
                              ... wrong = 0
                              ... for x in range(1, max_val):
                              ... for y in range(1, max_val):
                              ... wrong += (x / num_type(y)) * y != x
                              ... return wrong
                              ...
                              >>>check_accura cy(float)
                              101502
                              >>>check_accura cy(Decimal)
                              310013
                              >>>check_accura cy(Fraction)
                              0
                              >
                              >
                              The conclusions I came to based on running that experiment are:
                              - Decimal actually appears to suffer more rounding problems than float
                              for rational arithmetic
                              Mmm, but I doubt that counting how many times the results are equal, is
                              the right way to evaluate "accuracy".
                              A stopped clock shows the right time twice a day; a clock that loses one
                              minute per day shows the right time once every two years. Clearly the
                              stopped clock is much better!


                              --
                              Gabriel Genellina

                              Comment

                              • Piet van Oostrum

                                #135
                                Re: How about adding rational fraction to Python?

                                >>>>"Gabriel Genellina" <gagsl-py2@yahoo.com.a r(GG) wrote:
                                >GGEn Tue, 04 Mar 2008 11:46:48 -0200, NickC <ncoghlan@gmail .comescribió:
                                >>A mildly interesting Py3k experiment:
                                >>>
                                >>Python 3.0a3+ (py3k:61229, Mar 4 2008, 21:38:15)
                                >>[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
                                >>Type "help", "copyright" , "credits" or "license" for more information.
                                >>>>>from fractions import Fraction
                                >>>>>from decimal import Decimal
                                >>>>>def check_accuracy( num_type, max_val=1000):
                                >>... wrong = 0
                                >>... for x in range(1, max_val):
                                >>... for y in range(1, max_val):
                                >>... wrong += (x / num_type(y)) * y != x
                                >>... return wrong
                                >>...
                                >>>>>check_accu racy(float)
                                >>101502
                                >>>>>check_accu racy(Decimal)
                                >>310013
                                >>>>>check_accu racy(Fraction)
                                >>0
                                >>>
                                >>>
                                >>The conclusions I came to based on running that experiment are:
                                >>- Decimal actually appears to suffer more rounding problems than float
                                >>for rational arithmetic
                                >GGMmm, but I doubt that counting how many times the results are equal, is
                                >GGthe right way to evaluate "accuracy".
                                >GGA stopped clock shows the right time twice a day; a clock that loses one
                                >GGminute per day shows the right time once every two years. Clearly the
                                >GGstopped clock is much better!
                                But if the answer is incorrect (in the float calculation) the error is
                                limited. IEEE 754 prescribes that the error should be at most 1 LSB, IIRC.
                                And then the number of errors is the proper measure.
                                --
                                Piet van Oostrum <piet@cs.uu.n l>
                                URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C 4]
                                Private email: piet@vanoostrum .org

                                Comment

                                Working...