Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Project: math480-2016
Views: 2158
area = dblquad(lambda x, y: log(abs( 4 - 2*cos(2*pi*x) - 2*cos(2*pi*y))), 0, 1, lambda x:0, lambda x:1)
area
(1.1662436161232819, 7.180621168198628e-09)

Another speed trick is fast_float.

This is something Robert Bradshaw wrote, originally to make 3d plotting faster. It takes a symbolic epxression and "compiles" it (very quickly) into an internal form that can be evaluated quickly.

See http://doc.sagemath.org/html/en/reference/misc/sage/ext/fast_eval.html

# how long does yours take? about 1s -- pretty bad? from scipy.integrate import quad, dblquad %time area = dblquad(lambda x, y: log(abs( 4 - 2*cos(2*pi*x) - 2*cos(2*pi*y))), 0, 1, lambda x:0, lambda x:1)
CPU time: 0.77 s, Wall time: 0.81 s
# try that trick I mentioned... and get a MASSIVE speedup. from scipy.integrate import quad, dblquad f(x,y) = log(abs( 4 - 2*cos(2*pi*x) - 2*cos(2*pi*y))) g = fast_float(f) %time area = dblquad(g, 0r, 1r, lambda x:0r, lambda x:1r)
CPU time: 0.00 s, Wall time: 0.00 s
# How much better? %timeit area0 = dblquad(g, 0r, 1r, lambda x:0r, lambda x:1r) %timeit area1 = dblquad(lambda x, y: log(abs( 4 - 2*cos(2*pi*x) - 2*cos(2*pi*y))), 0, 1, lambda x:0, lambda x:1)
625 loops, best of 3: 1.34 ms per loop 5 loops, best of 3: 780 ms per loop
780/1.34
582.089552238806
# Speedup by a factor of more than 500x! ︠dff64924-b26d-44fa-b3f3-91ddd385d4cei︠ %md **Exercise: ** Make up your own symbolic functions by copying how we wrote `f(x,y) = log(abs( 4 - 2*cos(2*pi*x) - 2*cos(2*pi*y)))` above, and compare the speed of evaluation using fast_float to the speed of a Python function `def f(x,y): ...` that does the same thing.

**Exercise: ** Make up your own symbolic functions by copying how we wrote f(x,y) = log(abs( 4 - 2*cos(2*pi*x) - 2*cos(2*pi*y))) above, and compare the speed of evaluation using fast_float to the speed of a Python function def f(x,y): ... that does the same thing.

f(x,y) = x+y # change this f0 = fast_float(f) def g(x,y): return x+y # change this
# rerun this after changing the above... x = float(5); y = float(7) %timeit f(x,y) %timeit f0(x,y) %timeit g(x,y)
# How much faster?!