Permalink
Browse files

mostly done with mandelbrot

  • Loading branch information...
1 parent d762231 commit a2922a243c3f77b45775db05ea4b57cec6926e37 @robertwb robertwb committed Feb 11, 2009
Showing with 48 additions and 46 deletions.
  1. +48 −46 mandelbrot_cython.pyx
View
94 mandelbrot_cython.pyx
@@ -1,50 +1,52 @@
# The Computer Language Benchmarks Game
# http://shootout.alioth.debian.org/
#
-# contributed by Tupteq
-# modified by Simon Descarpentries
-
-import sys
-from array import array
-
-def main():
- cout = sys.stdout.write
- size = int(sys.argv[1])
- fsize = float(size)
- xr_size = xrange(size)
- xr_iter = xrange(50)
- bit_num = 7
- byte_acc = 0
- result = []
- local_abs = abs
-
- cout ("P4\n%d %d\n" % (size, size))
-
- for y in xr_size:
- fy = 2j * y / fsize - 1j
- for x in xr_size:
- z = 0j
- c = 2. * x / fsize - 1.5 + fy
-
- for i in xr_iter:
- z = z * z + c
- if local_abs(z) >= 2.: break
- else:
- byte_acc += 1 << bit_num
-
- if bit_num == 0:
- result.append (byte_acc)
- bit_num = 7
- byte_acc = 0
- else:
- bit_num -= 1
-
- if bit_num != 7:
- result.append (byte_acc)
- bit_num = 7
- byte_acc = 0
-
- cout (array ('B', result).tostring ())
-
-main()
+# contributed by Robert Bradshaw
+
+
+import sys
+
+def main(int size, outfile=sys.stdout):
+ cdef int iter = 50
+ cdef double step = 2.0 / size
+ cdef double Cx, Cy, Zx, Zy, abs2
+ cdef double Zx2, Zy2
+ cdef int i, xi, yi
+ cdef double square_abs
+
+ cdef line = ' ' * ((size+7) // 8)
+ cdef char* buf = line
+ cdef unsigned char byte_acc
+
+ write = outfile.write
+ write("P4\n%s %s\n" % (size, size))
+
+
+ for yi in range(size):
+ byte_acc = 0
+ for xi in range(size):
+ Zx = Cx = step*xi - 1.5
+ Zy = Cy = step*yi - 1.0
+ i = 0
+ while True:
+ # Z = Z^2 + C
+ # Soon (hopefully) Cython will have native c complex types
+ Zx, Zy = Zx*Zx - Zy*Zy + Cx , 2*Zx*Zy + Cy
+ square_abs = Zx*Zx + Zy*Zy
+ i += 1
+ if (i > iter) | (square_abs > 4.0):
+ break
+
+ byte_acc = (byte_acc << 1) | (square_abs < 4.0)
+ if xi & 7 == 7:
+ buf[xi >> 3] = byte_acc
+
+ if size & 7 != 0:
+ # line ending on non-byte boundary
+ byte_acc <<= 8 - (size % 8)
+ buf[size >> 3] = byte_acc
+ write(line)
+
+
+#main()

0 comments on commit a2922a2

Please sign in to comment.