Commit 6dd63258 authored by Stefan Behnel's avatar Stefan Behnel

modernise demos and make them Py2/3 compatible

parent 9b925e03
from __future__ import absolute_import, print_function
import sys
f1 = open(sys.argv[1])
f2 = open(sys.argv[2])
try:
if f1.read() != f2.read():
print ("Files differ")
print("Files differ")
sys.exit(1)
else:
print ("Files identical")
print("Files identical")
finally:
f1.close()
f2.close()
# cython: language_level=3
print __name__
print(__name__)
if __name__ == "__main__":
print "Hi, I'm embedded."
print("Hi, I'm embedded.")
else:
print "I'm being imported."
print("I'm being imported.")
# cython: language_level=3
import lcmath
def nCr(n, r):
"""Return the number of ways to choose r elements of a set of n."""
return lcmath.exp( lcmath.lfactorial(n) - lcmath.lfactorial(r)
- lcmath.lfactorial(n-r) )
return lcmath.exp(
lcmath.lfactorial(n) -
lcmath.lfactorial(r) -
lcmath.lfactorial(n-r)
)
if __name__ == "__main__":
import sys
......@@ -11,4 +17,4 @@ if __name__ == "__main__":
sys.stderr.write("USAGE: %s n r\nPrints n-choose-r.\n" % sys.argv[0])
sys.exit(2)
n, r = map(float, sys.argv[1:])
print nCr(n, r)
print(nCr(n, r))
# cython: language_level=3
cdef extern from "math.h":
double c_lgamma "lgamma" (double)
double c_exp "exp" (double)
def exp(n):
"""Return e**n."""
return c_exp(n)
def lfactorial(n):
"""Return an estimate of the log factorial of n."""
return c_lgamma(n+1)
def factorial(n):
"""Return an estimate of the factorial of n."""
return c_exp( c_lgamma(n+1) )
......@@ -21,4 +26,4 @@ if __name__ == "__main__":
sys.stderr.write("USAGE: %s n\nPrints n!.\n" % sys.argv[0])
sys.exit(2)
n, = map(float, sys.argv[1:])
print factorial(n)
print(factorial(n))
# cython: language_level=3
def f(x):
return x**2-x
def integrate_f(a, b, N):
s = 0.0
dx = (b-a)/N
......
# cython: language_level=3
cdef double f(double x) except? -2:
return x**2-x
def integrate_f(double a, double b, int N):
cdef int i
s = 0.0
......
from __future__ import absolute_import, print_function
import timeit
import integrate0, integrate1, integrate2
......@@ -5,9 +7,9 @@ import integrate0, integrate1, integrate2
number = 10
py_time = None
for m in ('integrate0', 'integrate1', 'integrate2'):
print m
print(m)
t = min(timeit.repeat("integrate_f(0.0, 10.0, 10000000)", "from %s import integrate_f" % m, number=number))
if py_time is None:
py_time = t
print " ", t / number, "s"
print " ", py_time / t
print(" ", t / number, "s")
print(" ", py_time / t)
from __future__ import absolute_import, print_function
import os
import sys
......@@ -8,7 +10,7 @@ from Cython.Build import cythonize
# For demo purposes, we build our own tiny library.
try:
print "building libmymath.a"
print("building libmymath.a")
assert os.system("gcc -shared -fPIC -c mymath.c -o mymath.o") == 0
assert os.system("ar rcs libmymath.a mymath.o") == 0
except:
......
cimport numpy
import numpy
cimport numpy as cnp
def sum_of_squares(numpy.ndarray[double, ndim=1] arr):
def sum_of_squares(cnp.ndarray[double, ndim=1] arr):
cdef long N = arr.shape[0]
cdef double ss = 0
for i in range(N):
......
# cython: language_level=3
# distutils: extra_compile_args = -O3
import cython
cimport cython
ctypedef fused INT:
int
......@@ -15,6 +16,7 @@ ctypedef fused C_INT:
unsigned int
unsigned long long
@cython.overflowcheck(False)
def fib(INT n):
"""
......@@ -54,12 +56,13 @@ def collatz(INT n):
cdef INT k = 0
while n != 1:
if n % 2 == 0:
n /= 2
n //= 2
else:
n = 3*n + 1
k += 1
return int(k)
@cython.overflowcheck(True)
@cython.overflowcheck.fold(False)
def collatz_overflow(INT n):
......@@ -74,12 +77,13 @@ def collatz_overflow(INT n):
cdef INT k = 0
while n != 1:
if n % 2 == 0:
n /= 2
n //= 2
else:
n = 3*n + 1
k += 1
return int(k)
@cython.overflowcheck(True)
@cython.overflowcheck.fold(True)
def collatz_overflow_fold(INT n):
......@@ -94,14 +98,13 @@ def collatz_overflow_fold(INT n):
cdef INT k = 0
while n != 1:
if n % 2 == 0:
n /= 2
n //= 2
else:
n = 3*n + 1
k += 1
return int(k)
@cython.overflowcheck(False)
def factorial(INT n):
"""
......@@ -129,7 +132,6 @@ def factorial_overflow(INT n):
return int(res)
@cython.overflowcheck(False)
def most_orthogonal(C_INT[:,::1] vectors):
cdef C_INT n = vectors.shape[0]
......@@ -148,6 +150,7 @@ def most_orthogonal(C_INT[:,::1] vectors):
min_pair = i, j
return vectors[i], vectors[j]
@cython.overflowcheck(True)
@cython.overflowcheck.fold(False)
def most_orthogonal_overflow(C_INT[:,::1] vectors):
......@@ -167,6 +170,7 @@ def most_orthogonal_overflow(C_INT[:,::1] vectors):
min_pair = i, j
return vectors[i], vectors[j]
@cython.overflowcheck(True)
@cython.overflowcheck.fold(True)
def most_orthogonal_overflow_fold(C_INT[:,::1] vectors):
......
from __future__ import absolute_import, print_function
from overflow_perf import *
import sys
......@@ -11,7 +13,7 @@ except ImportError:
def run_tests(N):
global f
for func in most_orthogonal, fib, collatz, factorial:
print func.__name__
print(func.__name__)
for type in ['int', 'unsigned int', 'long long', 'unsigned long long', 'object']:
if func == most_orthogonal:
if type == 'object' or np == None:
......@@ -23,15 +25,16 @@ def run_tests(N):
else:
arg = N
try:
print "%s[%s](%s)" % (func.__name__, type, N)
print("%s[%s](%s)" % (func.__name__, type, N))
with_overflow = my_timeit(globals()[func.__name__ + "_overflow"][type], arg)
no_overflow = my_timeit(func[type], arg)
print "\t%0.04e\t%0.04e\t%0.04f" % (no_overflow, with_overflow, with_overflow / no_overflow)
print("\t%0.04e\t%0.04e\t%0.04f" % (no_overflow, with_overflow, with_overflow / no_overflow))
if func.__name__ + "_overflow_fold" in globals():
with_overflow = my_timeit(globals()[func.__name__ + "_overflow_fold"][type], arg)
print "\t%0.04e\t%0.04e\t%0.04f" % (no_overflow, with_overflow, with_overflow / no_overflow), "(folded)"
print("\t%0.04e\t%0.04e\t%0.04f (folded)" % (
no_overflow, with_overflow, with_overflow / no_overflow))
except OverflowError:
print " ", "Overflow"
print(" ", "Overflow")
def my_timeit(func, N):
global f, arg
......@@ -44,10 +47,11 @@ def my_timeit(func, N):
break
return res / times
params = sys.argv[1:]
if not params:
params = [129, 9, 97]
for arg in params:
print
print "N", arg
print()
print("N", arg)
run_tests(int(arg))
print "starting"
# cython: language_level=3
print("starting")
def primes(int kmax):
# cdef int n, k, i
......@@ -10,11 +12,11 @@ def primes(int kmax):
n = 2
while k < kmax:
i = 0
while i < k and n % p[i] <> 0:
i = i + 1
while i < k and n % p[i] != 0:
i += 1
if i == k:
p[k] = n
k = k + 1
k += 1
result.append(n)
n = n + 1
n += 1
return result
from __future__ import absolute_import, print_function
import sys
from primes import primes
if len(sys.argv) >= 2:
n = int(sys.argv[1])
else:
n = 1000
print primes(n)
print(primes(n))
from __future__ import absolute_import, print_function
from spam import Spam
s = Spam()
print "Created:", s
print("Created:", s)
s.set_amount(42)
print "Amount =", s.get_amount()
print("Amount =", s.get_amount())
s.describe()
s = None
# cython: language_level=3
#
# Example of an extension type.
#
......@@ -9,7 +11,7 @@ cdef class Spam:
self.amount = 0
def __dealloc__(self):
print self.amount, "tons of spam is history."
print(self.amount, "tons of spam is history.")
def get_amount(self):
return self.amount
......@@ -18,4 +20,4 @@ cdef class Spam:
self.amount = new_amount
def describe(self):
print self.amount, "tons of spam!"
print(self.amount, "tons of spam!")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment