CoCalc Public Fileswww / talks / pyrex / misc / mult2.pyxOpen with one click!
Author: William A. Stein
1
"""
2
Build as follows:
3
4
# pyrex mult2.pyx
5
# ls -lh mult2.c
6
-rw-r--r-- 1 was was 28K Nov 11 14:09 mult2.c
7
# gcc -shared -O3 -fPIC -I/home/was/local/include/python2.4 mult2.c -o mult2.so
8
-rwxr-xr-x 1 was was 21K Nov 11 14:13 mult2.so
9
10
(Your Python include directory is probably different than mine.)
11
"""
12
13
cdef extern from "Python.h":
14
void* PyMem_Malloc(int)
15
void PyMem_Free(void *p)
16
17
cdef class Matrix:
18
cdef int *entries
19
cdef int p, n
20
21
def __new__(self, int p, int n, entries=None):
22
self.n = n
23
self.p = p
24
self.entries = <int*> PyMem_Malloc(sizeof(int)*n*n)
25
26
def __dealloc__(self):
27
PyMem_Free(self.entries)
28
29
def __init__(self, int p, int n, entries=None):
30
"""
31
Create a matrix over a finite field.
32
INPUT:
33
p -- prime
34
n -- positive integer
35
entries -- entries of the matrix (defaults to None, which means 0 matrix).
36
"""
37
cdef int i, j, k, x
38
if entries != None:
39
for i from 0 <= i < self.n:
40
for j from 0 <= j < self.n:
41
k = i*self.n + j
42
x = entries[k] % p
43
if x<0: x = x + p
44
self.entries[k] = x
45
else:
46
for i from 0 <= i < self.n:
47
for j from 0 <= j < self.n:
48
self.entries[i*self.n + j] = 0
49
50
def __repr__(self):
51
cdef int i, j, n
52
s = ""
53
n = self.n
54
for i from 0 <= i < n:
55
for j from 0 <= j < n:
56
s = s + "%s, "%self.entries[n*i + j]
57
s = s + "\n"
58
return s
59
60
cdef Matrix __mul__(Matrix self, Matrix B):
61
cdef int s, i, j, k, n
62
cdef Matrix ans
63
ans = Matrix(self.p, self.n)
64
n = self.n
65
for i from 0 <= i < n:
66
for j from 0 <= j < n:
67
# The i,j entry of the product
68
s = 0
69
for k from 0 <= k < n:
70
s = (s + (self.entries[i*n+k] * B.entries[k*n+j])) % self.p
71
if s < 0: s = s + self.p
72
ans.entries[i*n+j] = s
73
return ans
74
75