gazoni / pyeuclid

Automatically exported from code.google.com/p/pyeuclid
0 stars 0 forks source link

Matrix3 is missing determinant and inverse #11

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
The Matrix3 class is missing determinant() and invert() classes that are 
crucial for 2D geometry.

Original issue reported on code.google.com by dov.grob...@gmail.com on 26 Feb 2011 at 10:53

GoogleCodeExporter commented 8 years ago
Here is code that adds this functionality:

    def determinant(self):
        return (a*f*k 
                + b*g*i 
                + c*e*j 
                - a*g*j 
                - b*e*k 
                - c*f*i)

    def inverse(self):
        tmp = Matrix3()
        d = self.determinant()

        if abs(d) < 0.001:
            # No inverse, return identity
            return tmp
        else:
            d = 1.0 / d

            tmp.a = d * (self.f*self.k - self.g*self.j)
            tmp.b = d * (self.c*self.j - self.b*self.k)
            tmp.c = d * (self.b*self.g - self.c*self.f)
            tmp.e = d * (self.g*self.i - self.e*self.k)
            tmp.f = d * (self.a*self.k - self.c*self.i)
            tmp.g = d * (self.c*self.e - self.a*self.g)
            tmp.i = d * (self.e*self.j - self.f*self.i)
            tmp.j = d * (self.b*self.i - self.a*self.j)
            tmp.k = d * (self.a*self.f - self.b*self.e)

            return tmp

This code was automatically created by the following program:

#!/usr/bin/python

"""
Create code for determinant and inversion of a 3x3 matrix
for pyeuclid.

This code is in the public domain.

Dov Grobgeld <dov.grobgeld@gmail.com>
Saturday 2011-03-12 23:44 
"""

import sympy
import re

syms = 'abcefgijk'
for v in syms:
    locals()[v]=sympy.Symbol(v)

M = sympy.Matrix([[a,b,c],
                  [e,f,g],
                  [i,j,k]])

# Create determinant and rewrite the string expression
det = M.det()
expr = re.sub(r'([\+\-])', '\n                \\1',
              re.sub(r"\b(["+syms+"])\b", r'self.\1',
                     str(det)))
print "    def determinant(self):"
print "        return (" + expr + ")"

print """
    def inverse(self):
        tmp = Matrix3()
        d = self.determinant()

        if abs(d) < 0.001:
            # No inverse, return identity
            return tmp
        else:
            d = 1.0 / d
"""

# Invert, rewrite, and output
Minv = sympy.cancel(det*M.inv())
for idx in range(9):
    expr = Minv[idx]
    print ("            tmp."
           +syms[idx]
           +" = d * ("
           +re.sub(r"\b([abcefgijk])\b", r'self.\1', str(expr))
           +")")
print "\n            return tmp"

Original comment by dov.grob...@gmail.com on 12 Mar 2011 at 9:44

GoogleCodeExporter commented 8 years ago
Fixed in svn.

Original comment by dov.grob...@gmail.com on 13 Mar 2011 at 8:02