Skip to content

Instantly share code, notes, and snippets.

@andim
Created June 10, 2014 00:25
Show Gist options
  • Save andim/ceafc011b5c7d3eef381 to your computer and use it in GitHub Desktop.
Save andim/ceafc011b5c7d3eef381 to your computer and use it in GitHub Desktop.
Comment on @rasbt's benchmark
def python_lstsqr(x, y):
""" Computes the least-squares solution to a linear matrix equation. """
len_x = len(x)
x_avg = sum(x)/len_x
y_avg = sum(y)/len(y)
var_x = 0
cov_xy = 0
var_x = np.sum((x - x_avg)**2)
cov_xy = np.sum((x - x_avg)*(y - y_avg))
slope = cov_xy / var_x
y_interc = y_avg - slope*x_avg
return (slope, y_interc)
%%cython
import numpy as np
cimport numpy as np
cimport cython
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef cython_lstsqr(x_ary, y_ary):
""" Computes the least-squares solution to a linear matrix equation. """
cdef double x_avg, y_avg, var_x, cov_xy,\
slope, y_interc, temp
cdef double[:] x = x_ary # memory view
cdef double[:] y = y_ary
cdef long N
cdef int i
N = x.shape[0]
x_avg = np.sum(x)/N
y_avg = np.sum(y)/N
var_x = 0
cov_xy = 0
for i in range(N):
temp = (x[i] - x_avg)
var_x += temp**2
cov_xy += temp*(y[i] - y_avg)
slope = cov_xy / var_x
y_interc = y_avg - slope*x_avg
return (slope, y_interc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment