how to make this code faster
Robert Kern
robert.kern at gmail.com
Thu Oct 13 02:29:56 EDT 2005
ajikoe at gmail.com wrote:
> def f(x,y):
> return math.sin(x*y) + 8 * x
> I have code like this:
>
> def main():
> n = 2000
> a = zeros((n,n), Float)
> xcoor = arange(0,1,1/float(n))
> ycoor = arange(0,1,1/float(n))
>
>
> for i in range(n):
> for j in range(n):
> a[i,j] = f(xcoor[i], ycoor[j]) # f(x,y) = sin(x*y) + 8*x
>
> print a[1000,1000]
> pass
>
> if __name__ == '__main__':
> main()
Ufuncs are your friend:
from scipy import *
def f(x, y):
return sin(x*y) + 8*x
def main():
n = 2000
ycoor = linspace(0.0, 1.0, n)
xcoor = transpose(atleast_2d(ycoor))
a = f(xcoor, ycoor)
print a[1000, 1000]
--
Robert Kern
rkern at ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
More information about the Python-list
mailing list