During October (2017) I will write a program per day for some well-known numerical methods in both Python and Julia. It is intended to be an exercise then don't expect the code to be good enough for real use. Also, I should mention that I have almost no experience with Julia, so it probably won't be idiomatic Julia but more Python-like Julia.
Following are the codes.
from __future__ import division, print_function import numpy as np def simps(y, x=None, dx=1.0): n = len(y) if x is None: inte = np.sum(y[0:n-2:2] + 4*y[1:n-1:2] + y[2:n:2])*dx else: dx = x[1::2] - x[:-1:2] inte = np.dot(y[0:n-2:2] + 4*y[1:n-1:2] + y[2:n:2], dx) return inte/3 n = 21 x = np.linspace(0, 10, n) y = np.sin(x) print(simps(y, x=x)) print(1 - np.cos(10))
function simps(y; x=nothing, dx=1.0) n = length(y) if x == nothing inte = sum(y[1:2:n-2] + 4*y[2:2:n-1] + y[3:2:n])*dx else dx = x[2:2:end] - x[1:2:end-1] inte = (y[1:2:n-2] + 4*y[2:2:n-1] + y[3:2:n])' * dx end return inte/3 end n = 21 x = linspace(0, 10, n) y = sin.(x) println(simps(y, x=x)) println(1 - cos(10))
Regarding number of lines we have: 19 in Python and 17 in Julia. The comparison
in execution time is done with
%timeit magic command in IPython and
@benchmark in Julia.
In this case, we can say that the Python code is 10 times slower than Julia.