Decimal place issues with floats and decimal.Decimal

前端 未结 6 1560
悲哀的现实
悲哀的现实 2020-11-29 10:47

I seem to be losing a lot of precision with floats.

For example I need to solve a matrix:

4.0x -2.0y 1.0z =11.0
1.0x +5.0y -3.0z =-6.0
2.0x +2.0y +5.         


        
6条回答
  •  猫巷女王i
    2020-11-29 11:42

    I'd caution against the decimal module for tasks like this. Its purpose is really more dealing with real-world decimal numbers (eg. matching human bookkeeping practices), with finite precision, not performing exact precision math. There are numbers not exactly representable in decimal just as there are in binary, and performing arithmetic in decimal is also much slower than alternatives.

    Instead, if you want exact results you should use rational arithmetic. These will represent numbers as a numerator/denomentator pair, so can exactly represent all rational numbers. If you're only using multiplication and division (rather than operations like square roots that can result in irrational numbers), you will never lose precision.

    As others have mentioned, python 2.6 will have a built-in rational type, though note that this isn't really a high-performing implementation - for speed you're better using libraries like gmpy. Just replace your calls to float() to gmpy.mpq() and your code should now give exact results (though you may want to format the results as floats for display purposes).

    Here's a slightly tidied version of your code to load a matrix that will use gmpy rationals instead:

    def read_matrix(f):
        b,y = [], []
        for line in f:
            bits = line.split(",")
            b.append( map(gmpy.mpq, bits[:-1]) )
            y.append(gmpy.mpq(bits[-1]))
        return b,y
    

提交回复
热议问题