Search code examples
pythonmathnumerical

whether to use python to the huge computing?


Sorry for my bad English.I am currently work with python and i have a problem with too slow to filling of matrix size of 10000x10000.I program a "relaxation method" where i need to test the different size of matrix.What do you think about that?...P.S I wait 3-5 min to fill one matrix 10000x10000.

    def CalcMatrix(self):
    for i in range(0, self._n + 1):                       #(0,10000)
        for j in range(0, self._n + 1):                   #(0,10000)
                one = sin(pi * self._x[i])                # x is the vector of size 10000
                two = sin(pi * self._y[j])                # y too
                self._f[i][j] = 2 * pi * pi * one * two   #fill 

Solution

  • Native Python loop speed is very slow. People working with arrays and matrices in Python usually use numpy. There are other tools like cython and numba which can dramatically improve the speed in certain circumstances, but the basic idea of numpy is to vectorize the operations and push the hard work down to fast libraries implemented in C and fortran.

    The following code takes only a few seconds on my not-very-fast notebook:

    import numpy as np
    from numpy import pi
    x = np.linspace(0,1,10**4)
    y = np.linspace(2,5,10**4)
    ans = 2*pi**2 * np.outer(np.sin(pi*x), np.sin(pi*y))
    

    (PS: If your _n == 10000, then won't your matrix be 10001x10001, not 10000x10000?)