├── C ├── .munchausen_number.c.swp ├── c_job_script ├── test_belief_propagation.c ├── test_copy_matrix.c ├── test_evaluate_functions.c ├── test_fibonacci.c ├── test_gauss_legendre_quadrature.c ├── test_laplace_jacobi_4.c ├── test_look_and_say.c ├── test_markov_chain.c ├── test_matrix_multiplication.c ├── test_munchausen_number.c └── test_pernicious_numbers.c ├── COPYRIGHT ├── Data ├── bible.txt ├── book1.txt ├── create_nc4Files.py ├── plrabn12.txt └── world192.txt ├── Fortran ├── ._fortranJobScript.job ├── fortran_job_script ├── munchausen_number.F90 ├── test_belief_propagation.F90 ├── test_copy_matrix.F90 ├── test_evaluate_functions.F90 ├── test_fibonacci.F90 ├── test_gauss_legendre_quadrature.F90 ├── test_laplace_jacobi_4_loops.F90 ├── test_laplace_jacobi_4_vectorized.F90 ├── test_look_and_say.F90 ├── test_markov_chain.F90 ├── test_matrix_multiplication.F90 ├── test_matrix_multiplication_DGEMM.F90 ├── test_munchausen_number.F90 ├── test_pernicious_numbers.F90 └── timer_module.F90 ├── IDL ├── .DS_Store ├── ._.DS_Store ├── brm_gau_leg_54.pro ├── idl_job_script ├── run_all_scripts.pro ├── test_belief_propagation.pro ├── test_compute_fft.pro ├── test_copy_matrix.pro ├── test_evaluate_functions.pro ├── test_fibonacci.pro ├── test_gauss_legendre_quadrature.pro ├── test_laplace_jacobi_4.pro ├── test_look_and_say.pro ├── test_markov_chain.pro ├── test_matrix_multiplication.pro ├── test_munchausen_number.pro ├── test_pernicious_numbers.pro ├── test_time_series_aoa.pro └── timeSeriesRun.pro ├── Java ├── .Java2019log-33588669.out.swp ├── java_job_script ├── testBeliefPropagation.java ├── testCopyMatrix.java ├── testCountUniqueWords.java ├── testEvaluateFunctions.java ├── testFibonacci.java ├── testGaussLegendreQuadrature.java ├── testLaplaceJacobi4.java ├── testLookAndSay.java ├── testMarkovChain.java ├── testMatrixMultiplication.java ├── testMunchausenNumber.java └── testPerniciousNumbers.java ├── Julia ├── .DS_Store ├── ._.DS_Store ├── ._Julia_2018log-33336899.out ├── ._Julia_2018log-33372690.out ├── ._juliaJobScript.job ├── ._test_belief_propagation.jl ├── ._test_compute_FFT.jl ├── ._test_copy_matrix.jl ├── ._test_count_unique_words.jl ├── ._test_evaluate_functions.jl ├── ._test_fibonacci.jl ├── ._test_gauss_legendre_quadrature.jl ├── ._test_laplace_jacobi_4.jl ├── ._test_look_and_say.jl ├── ._test_look_and_say_2.jl ├── ._test_markov_chain.jl ├── ._test_matrix_multiplication.jl ├── ._test_munchausen.jl ├── ._test_sqrt_matrix.jl ├── ._test_time_series_AOA.jl ├── ._test_time_series_AOA_multiprocessing.jl ├── .ipynb_checkpoints │ ├── Untitled-checkpoint.ipynb │ └── test_laplace_jacobi_4-checkpoint.jl ├── julia_job_script ├── test_belief_propagation.jl ├── test_compute_FFT.jl ├── test_copy_matrix.jl ├── test_count_unique_words.jl ├── test_evaluate_functions.jl ├── test_fibonacci.jl ├── test_gauss_legendre_quadrature.jl ├── test_laplace_jacobi_4.jl ├── test_look_and_say.jl ├── test_look_and_say_2.jl ├── test_markov_chain.jl ├── test_matrix_multiplication.jl ├── test_munchausen.jl ├── test_pernicious_numbers.jl ├── test_read_reverse_file.jl ├── test_sqrt_matrix.jl ├── test_time_series_AOA.jl └── test_time_series_AOA_multiprocessing.jl ├── LICENSE.md ├── Matlab ├── matlab_job_script ├── test_belief_propagation.m ├── test_compute_FFT.m ├── test_copy_matrix.m ├── test_count_unique_words.m ├── test_evaluate_functions.m ├── test_fibonacci.m ├── test_fibonacci_iter.m ├── test_fibonacci_recur.m ├── test_gauss_legendre_quadrature.m ├── test_laplace_jacobi_4_loops.m ├── test_laplace_jacobi_4_vect.m ├── test_look_and_say.m ├── test_markov_chain.m ├── test_matrix_multiplication.m ├── test_munchausen_number.m ├── test_pernicious_numbers.m ├── test_sqrt_matrix.m ├── test_time_series_AOA.m └── timeSeries_AOA.m ├── Plots ├── fig_languages_histo_Aug2021.png ├── fig_languages_histo_May2020.png ├── fig_languages_histo_Sep2019.png ├── fig_languages_scatter_Aug2021.png ├── fig_languages_scatter_May2020.png ├── fig_languages_scatter_Sep2019.png ├── plot_timing_histo.py └── plot_timing_scatter.py ├── Python ├── .DS_Store ├── ._.DS_Store ├── ._Python local results.txt ├── ._README.txt ├── ._decoratorTimer.pyc ├── ._decorator_timer.py ├── ._pythonJobScript_Intel.job ├── ._pythonJobScript_discover.job ├── ._pythonJobScript_local.job ├── ._pythonJobScript_numba.job ├── ._test_belief_propagation.py ├── ._test_compute_FFT.py ├── ._test_copy_matrix.py ├── ._test_copy_matrix_numba.py ├── ._test_count_unique_words.py ├── ._test_digital_root.py ├── ._test_evaluate_functions.py ├── ._test_fibonacci.py ├── ._test_fibonacci_numba.py ├── ._test_gauss_legendre_quadrature.py ├── ._test_laplace_jacobi_4.py ├── ._test_laplace_jacobi_4_numba.py ├── ._test_look_and_say.py ├── ._test_markov_chain.py ├── ._test_matrix_multiplication.py ├── ._test_matrix_multiplication_numba.py ├── ._test_munchausen_number.py ├── ._test_sqrt_matrix.py ├── ._test_time_series_AOA.py ├── ._test_time_series_AOA_multiproc.py ├── __pycache__ │ └── benchmark_decorator.cpython-36.pyc ├── benchmark_decorator.py ├── python_job_script ├── python_job_script_numba ├── test_belief_propagation.py ├── test_belief_propagation_numba.py ├── test_compute_FFT.py ├── test_copy_matrix.py ├── test_copy_matrix_numba.py ├── test_count_unique_words.py ├── test_digital_root.py ├── test_evaluate_functions.py ├── test_evaluate_functions_numba.py ├── test_fibonacci.py ├── test_fibonacci_numba.py ├── test_gauss_legendre_quadrature.py ├── test_identity_file.py ├── test_laplace_jacobi_4.py ├── test_laplace_jacobi_4_numba.py ├── test_look_and_say.py ├── test_markov_chain.py ├── test_matrix_multiplication.py ├── test_matrix_multiplication_numba.py ├── test_munchausen_number.py ├── test_pernicious_numbers.py ├── test_sqrt_matrix.py ├── test_time_series_AOA.py └── test_time_series_AOA_multiproc.py ├── R ├── .RData ├── .Rhistory ├── ._.Rhistory ├── ._rJobScript.job ├── ._solver_order_4.R ├── ._test_belief_propagation.R ├── ._test_compute_FFT.R ├── ._test_copy_matrix.R ├── ._test_count_unique_words.R ├── ._test_evaluate_functions.R ├── ._test_fibonacci.R ├── ._test_gauss_legendre_quadrature.R ├── ._test_get_data_from_file.R ├── ._test_get_levels.R ├── ._test_laplace_jacobi_4.R ├── ._test_look_and_say.R ├── ._test_markov_chain.R ├── ._test_matrix_multiplication.R ├── ._test_munchausen_number.R ├── ._test_sqrt_matrix.R ├── ._test_time_series_AOA.R ├── ._test_time_series_AOA_multiproc.R ├── ._vertLevels_GEOS5.R ├── r_job_script ├── solver_order_4.R ├── test_belief_propagation.R ├── test_compute_FFT.R ├── test_copy_matrix.R ├── test_count_unique_words.R ├── test_evaluate_functions.R ├── test_fibonacci.R ├── test_gauss_legendre_quadrature.R ├── test_get_data_from_file.R ├── test_get_levels.R ├── test_laplace_jacobi_4.R ├── test_look_and_say.R ├── test_markov_chain.R ├── test_matrix_multiplication.R ├── test_munchausen_number.R ├── test_pernicious_numbers.R ├── test_sqrt_matrix.R ├── test_time_series_AOA.R ├── test_time_series_AOA_multiproc.R └── vertLevels_GEOS5.R ├── README.md ├── Results ├── timing_results_Aug2021.txt ├── timing_results_May2020.txt └── timing_results_Sep2019.txt ├── Scala ├── DoBeliefPropagation.scala ├── DoBelief_jama.scala ├── DoCopyMatrix.scala ├── DoCountUniqueWords.scala ├── DoEvaluateFunctions.scala ├── DoFibonacci.scala ├── DoLaplaceJacobi4.scala ├── DoLookAndSay.scala ├── DoMarkovChain.scala ├── DoMatrixMultiplication.scala ├── DoMatrixMultiplicationJama.scala ├── DoMatrixMultiplicationLa4j.scala ├── DoMunchausenNumber.scala └── scala_job_script ├── _config.yml └── docs ├── 2017edition.pdf ├── 2018edition.pdf └── 2019edition.pdf /C/.munchausen_number.c.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/C/.munchausen_number.c.swp -------------------------------------------------------------------------------- /C/test_belief_propagation.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | const int Dim = 1000; 10 | 11 | void belief_propagation(double A[Dim][Dim], double x[Dim], int N); 12 | 13 | int main(int argc, char* argv[]) { 14 | double A[Dim][Dim]; 15 | double x[Dim]; 16 | double max_rand; 17 | int N, i, j, Dim; 18 | clock_t start, finish; 19 | 20 | // Get the number of iterations from the command line 21 | N = atoi(argv[1]); 22 | 23 | srand(time(NULL)); 24 | start = clock(); 25 | 26 | max_rand = (double)RAND_MAX; 27 | for (i = 0; i < Dim; i++) { 28 | x[i] = 1.0; 29 | for (j = 0; j < Dim; j++) 30 | A[i][j] = rand()/max_rand; 31 | } 32 | 33 | // Perform the belief operations 34 | belief_propagation( A, x, N); 35 | finish = clock(); 36 | 37 | printf("Time for Belief Propagation (%d): %lf s\n", N, (double) (finish - start)/CLOCKS_PER_SEC); 38 | return 0; 39 | } 40 | 41 | void belief_propagation(double A[Dim][Dim], double x[Dim], int N) { 42 | int i, k, j; 43 | double x2[Dim]; 44 | for (k=0; k 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | double*** make_3D_double_arr(int arr_size_x, int arr_size_y, int arr_size_z); 17 | 18 | int main(int argc, char* argv[]) { 19 | double ***A; 20 | int dim, i, j, k; 21 | clock_t start, finish; 22 | double max_rand; 23 | 24 | // Get the dimension from the command line 25 | dim = atoi(argv[1]); 26 | 27 | // Allocate the array and fill it 28 | A = (double ***) malloc(dim * sizeof(double **)); 29 | for (i = 0; i < dim; i++) { 30 | A[i] = (double **) malloc(dim * sizeof(double *)); 31 | for (j = 0; j < dim; j++) { 32 | A[i][j] = (double *) malloc(3 * sizeof(double)); 33 | } 34 | } 35 | 36 | srand(time(NULL)); 37 | max_rand = (double)RAND_MAX; 38 | for (i = 0; i < dim; i++) { 39 | for (j = 0; j < dim; j++) { 40 | for (k = 0; k < 3; k++) { 41 | A[i][j][k] = rand()/max_rand; 42 | } 43 | } 44 | } 45 | 46 | 47 | // Perform the copy operations 48 | start = clock(); 49 | for (i = 0; i < dim; i++) { 50 | for (j = 0; j < dim; j++) { 51 | A[i][j][0] = A[i][j][1]; 52 | A[i][j][2] = A[i][j][0]; 53 | A[i][j][1] = A[i][j][2]; 54 | } 55 | } 56 | finish = clock(); 57 | 58 | printf("Time for matrix copy (%d): %lf s\n", dim, (double) (finish - start)/CLOCKS_PER_SEC); 59 | return 0; 60 | } 61 | 62 | double*** make_3D_double_arr(int arr_size_x, int arr_size_y, int arr_size_z) { 63 | double*** double_array; 64 | int i, j; 65 | double_array = (double***) malloc(arr_size_x*sizeof(double**)); 66 | for (i = 0; i < arr_size_x; i++) { 67 | double_array[i] = (double**) malloc(arr_size_y*sizeof(double*)); 68 | for (j = 0; j < arr_size_y; i++) { 69 | double_array[i][j] = (double*) malloc(arr_size_z*sizeof(double)); 70 | } 71 | } 72 | return double_array; 73 | } 74 | -------------------------------------------------------------------------------- /C/test_evaluate_functions.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | 10 | int main(int argc, char* argv[]) { 11 | double *x; 12 | double *y; 13 | double h; 14 | double a_min = -1500.0; 15 | double a_max = 1500.0; 16 | int num_iterations = 10000; 17 | int n, i, j, k; 18 | clock_t start, finish; 19 | double max_rand; 20 | 21 | // Get the dimension from the command line 22 | n = atoi(argv[1]); 23 | 24 | start = clock(); 25 | 26 | // Allocate the array and fill it 27 | x = (double *) malloc(n * sizeof(double)); 28 | y = (double *) malloc(n * sizeof(double)); 29 | 30 | h = (a_max - a_min)/(n-1); 31 | for (i = 0; i < n; i++) { 32 | x[i] = a_min + i*h; 33 | } 34 | 35 | for (i = 0; i < num_iterations; i++) { 36 | for (j = 0; j < n; j++) { 37 | y[j] = sin(x[j]); 38 | x[j] = asin(y[j]); 39 | y[j] = cos(x[j]); 40 | x[j] = acos(y[j]); 41 | y[j] = tan(x[j]); 42 | x[j] = atan(y[j]); 43 | } 44 | } 45 | 46 | finish = clock(); 47 | 48 | printf("Time Evaluate Function (%d): %lf s\n", n, (double) (finish - start)/CLOCKS_PER_SEC); 49 | return 0; 50 | } 51 | 52 | -------------------------------------------------------------------------------- /C/test_fibonacci.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | double recursive_fib(int n); 10 | long long int iterative_fib(int n); 11 | // double iterative_fib(int n); 12 | 13 | int main(int argc, char* argv[]) { 14 | int N, M, n1; 15 | clock_t start, finish; 16 | 17 | // Get the number of iterations from the command line 18 | N = atoi(argv[1]); 19 | M = N; 20 | 21 | srand(time(NULL)); 22 | 23 | // Perform the Recursive Fibonnacy operations 24 | start = clock(); 25 | 26 | n1 = iterative_fib(N); 27 | finish = clock(); 28 | 29 | printf("Iterative - Fibonnaci (%d): %lf s --> %d \n", N, (double) (finish - start)/CLOCKS_PER_SEC, n1); 30 | // Perform the Recursive Fibonnacy operations 31 | start = clock(); 32 | 33 | n1 = recursive_fib(M); 34 | finish = clock(); 35 | 36 | printf("Recursive - Fibonnaci (%d): %lf s --> %d \n", M, (double) (finish - start)/CLOCKS_PER_SEC, n1); 37 | return 0; 38 | } 39 | 40 | double recursive_fib(int n) { 41 | if(n <= 2) { 42 | return(1.0); 43 | } 44 | else { 45 | return(recursive_fib(n-2) + recursive_fib(n-1)); 46 | } 47 | } 48 | 49 | // Modifed from https://rosettacode.org/wiki/Fibonacci_sequence 50 | long long int iterative_fib(int n) { 51 | int fib_now = 0, fib_next = 1, temp_fib; 52 | while(--n > 0) { 53 | temp_fib = fib_now + fib_next; 54 | fib_now = fib_next; 55 | fib_next = temp_fib; 56 | } 57 | return fib_next; 58 | } 59 | -------------------------------------------------------------------------------- /C/test_gauss_legendre_quadrature.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | 9 | #define N 70 10 | 11 | const double Pi = atan2(1, 1)*4; 12 | double lroots[N]; 13 | double weight[N]; 14 | double lcoef[N + 1][N + 1] = {{0}}; 15 | 16 | void lege_coef() { 17 | int n, i; 18 | lcoef[0][0] = lcoef[1][1] = 1; 19 | for (n = 2; n <= N; n++) { 20 | lcoef[n][0] = -(n - 1)*lcoef[n - 2][0]/n; 21 | for (i = 1; i <= n; i++) { 22 | lcoef[n][i] = ((2*n - 1)*lcoef[n - 1][i - 1] - (n - 1)*lcoef[n - 2][i])/n; 23 | } 24 | } 25 | } 26 | 27 | double lege_eval(int n, double x) { 28 | int i; 29 | double s = lcoef[n][n]; 30 | for (i = n; i; i--) { 31 | s = s*x + lcoef[n][i - 1]; 32 | } 33 | return s; 34 | } 35 | 36 | double lege_diff(int n, double x) { 37 | return n*(x*lege_eval(n, x) - lege_eval(n - 1, x))/(x*x - 1); 38 | } 39 | 40 | void lege_roots() { 41 | int i; 42 | double x, x1; 43 | double eps = 1.0e-4; 44 | for (i = 1; i <= N; i++) { 45 | x = cos(Pi*(i - .25)/(N + .5)); 46 | do { 47 | x1 = x; 48 | x -= lege_eval(N, x)/lege_diff(N, x); 49 | } while ( fabs(x - x1) > 1.0e-16); 50 | // } while (x != x1); 51 | lroots[i - 1] = x; 52 | x1 = lege_diff(N, x); 53 | weight[i - 1] = 2 / ((1 - x * x) * x1 * x1); 54 | } 55 | } 56 | 57 | double lege_inte(double (*f)(double), double a, double b) { 58 | double c1 = (b - a) / 2, c2 = (b + a) / 2, sum = 0; 59 | int i; 60 | for (i = 0; i < N; i++) { 61 | sum += weight[i] * f(c1 * lroots[i] + c2); 62 | } 63 | return c1 * sum; 64 | } 65 | 66 | int main() { 67 | clock_t start, finish; 68 | int i; 69 | 70 | srand(time(NULL)); 71 | start = clock(); 72 | 73 | lege_coef(); 74 | lege_roots(); 75 | lege_inte(exp, -3, 3); 76 | 77 | finish = clock(); 78 | printf("Time for quadrature (%d): %lf s\n", N, (double) (finish - start)/CLOCKS_PER_SEC); 79 | 80 | //printf("Roots: "); 81 | //for (i = 0; i < N; i++) { 82 | // printf(" %g", lroots[i]); 83 | //} 84 | 85 | //printf("\nWeight:"); 86 | //for (i = 0; i < N; i++) { 87 | // printf(" %g", weight[i]); 88 | //} 89 | 90 | printf("\nintegrating Exp(x) over [-3, 3]:\n\t%10.8f,\n" 91 | "compred to actual\n\t%10.8f\n", 92 | lege_inte(exp, -3, 3), exp(3) - exp(-3)); 93 | finish = clock(); 94 | 95 | return 0; 96 | } 97 | -------------------------------------------------------------------------------- /C/test_look_and_say.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main(int argc, char* argv[]) { 8 | char *a = malloc(2), *b = 0, *x, c; 9 | int count, n, iter = 1, len = 1; 10 | clock_t start, finish; 11 | 12 | n = atoi(argv[1]); // 10; 13 | iter = 0; 14 | 15 | srand(time(NULL)); 16 | start = clock(); 17 | 18 | for (sprintf(a, "1223334444"); (b = realloc(b, len * 2 + 1)); a = b, b = x) { 19 | iter++; 20 | x = a; 21 | for (len = 0, count = 1; (c = *a); ) { 22 | if (c == *++a) { 23 | count++; 24 | } 25 | else if (c) { 26 | len += sprintf(b + len, "%d%c", count, c); 27 | count = 1; 28 | } 29 | } 30 | if (iter == n) 31 | break; 32 | } 33 | 34 | finish = clock(); 35 | // printf("sequence %s \n", x); 36 | 37 | printf("Time for look and say sequence (%d): %lf s\n", n, (double) (finish - start)/CLOCKS_PER_SEC); 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /C/test_markov_chain.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | double f(double *x); 9 | 10 | void mcmc(double *x, int N); 11 | 12 | int main(int argc, char* argv[]) { 13 | double x[2]; 14 | int N; 15 | int i, j, dim; 16 | clock_t start, finish; 17 | 18 | // Get the number of iterations from the command line 19 | N = atoi(argv[1]); 20 | 21 | srand(time(NULL)); 22 | 23 | // Perform the Markov Chain operations 24 | start = clock(); 25 | x[0] = 0.0; 26 | x[1] = 0.0; 27 | mcmc(x, N); 28 | finish = clock(); 29 | 30 | printf("Time for belief calculations (%d): %lf s\n", N, (double) (finish - start)/CLOCKS_PER_SEC); 31 | return 0; 32 | } 33 | 34 | double f(double *x) { 35 | return exp(sin(x[0]*5) - x[0]*x[0] - x[1]*x[1]); 36 | } 37 | 38 | #define pi 3.141592653589793 39 | void mcmc(double *x,int N){ 40 | double p = f(x); 41 | int n; 42 | double x2[2]; 43 | for(n=0; n 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | double** make_2d_array_double(int array_size_x, int array_size_y); 8 | 9 | int main( int argc, char *argv[] ) { 10 | double **A, **B, **C; 11 | int i, j, k; 12 | int dim; 13 | clock_t start, finish; 14 | 15 | dim = atoi(argv[1]); 16 | 17 | A = malloc(sizeof(double *) * dim); 18 | B = malloc(sizeof(double *) * dim); 19 | C = malloc(sizeof(double *) * dim); 20 | for (i = 0; i < dim; i++) { 21 | A[i] = malloc(sizeof(double) * dim); 22 | B[i] = malloc(sizeof(double) * dim); 23 | C[i] = malloc(sizeof(double) * dim); 24 | } 25 | 26 | double max_rand; 27 | 28 | srand(time(NULL)); 29 | max_rand = (double)RAND_MAX; 30 | for (i = 0; i < dim; i++) { 31 | for (j = 0; j < dim; j++) { 32 | A[i][j] = rand()/max_rand; 33 | B[i][j] = rand()/max_rand; 34 | } 35 | } 36 | 37 | start = clock(); 38 | 39 | for (i = 0; i < dim; i++) { 40 | for (j = 0; j < dim; j++) { 41 | C[i][j] = 0.; 42 | } 43 | for (k = 0; k < dim; k++) { 44 | for (j = 0; j < dim; j++) { 45 | C[i][j] += A[i][k]*B[k][j]; 46 | } 47 | } 48 | } 49 | 50 | finish = clock(); 51 | 52 | printf("time for C(%d,%d) = A(%d,%d) B(%d,%d) is %lf s\n", dim, dim, dim, dim, dim, dim, 53 | (double) (finish - start)/CLOCKS_PER_SEC); 54 | 55 | return 0; 56 | } 57 | 58 | double** make_2d_array_double(int array_size_x, int array_size_y) { 59 | double** array_double_2D; 60 | int i; 61 | array_double_2D = (double**) malloc(array_size_x*sizeof(double*)); 62 | for (i = 0; i < array_size_x; i++) { 63 | array_double_2D[i] = (double*) malloc(array_size_y*sizeof(double)); 64 | } 65 | return array_double_2D; 66 | } 67 | -------------------------------------------------------------------------------- /C/test_munchausen_number.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | int raisedto(int n); 10 | 11 | int main(int argc, char* argv[]) { 12 | int n, i, number; 13 | int power_of_digits[10]; 14 | clock_t start, finish; 15 | 16 | srand(time(NULL)); 17 | 18 | // Find the four Munchausen numbers 19 | start = clock(); 20 | 21 | for (i=0; i<10; i++) { 22 | power_of_digits[i] = raisedto(i); 23 | // printf("%d %d \n", i, power_of_digits[i]); 24 | } 25 | 26 | n = 0; 27 | i = 0; 28 | 29 | while(n < 4) { 30 | int sum = 0; 31 | for (number = i; number > 0; number /= 10) { 32 | int digit = number % 10; 33 | // find the sum of the digits raised to themselves 34 | sum += power_of_digits[digit]; 35 | } 36 | if (sum == i) { 37 | n++; 38 | // the sum is equal to the number itself; 39 | // thus it is a munchausen number 40 | printf("Munchausen number %i: %i\n", n, i); 41 | } 42 | i++; 43 | } 44 | finish = clock(); 45 | printf("Munchausen numbers: %lf s \n", (double) (finish - start)/CLOCKS_PER_SEC); 46 | 47 | return 0; 48 | } 49 | 50 | int raisedto(int n) { 51 | if(n == 0) { 52 | return(0); 53 | } 54 | else { 55 | return((int) pow(n, n)); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /C/test_pernicious_numbers.c: -------------------------------------------------------------------------------- 1 | // ********************************************************** 2 | // Find the nth pernicious number. 3 | // 4 | // ********************************************************** 5 | 6 | #include 7 | #include 8 | 9 | typedef unsigned uint; 10 | uint is_pernicious(uint n) 11 | { 12 | uint c = 2693408940u; // int with all prime-th bits set 13 | while (n) c >>= 1, n &= (n - 1); // take out lowerest set bit one by one 14 | return c & 1; 15 | } 16 | 17 | int main(int argc, char* argv[]) { 18 | uint i, c; 19 | int n; 20 | clock_t start, finish; 21 | 22 | // Get a positive integer from the command line 23 | n = atoi(argv[1]); 24 | 25 | start = clock(); 26 | for (i = c = 0; c < n; i++) { 27 | if (is_pernicious(i)) { 28 | ++c; 29 | } 30 | } 31 | finish = clock(); 32 | printf("Pernicious number (%u): %lf s\n", i-1, (double) (finish - start)/CLOCKS_PER_SEC); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | Copyright (C) 2018 United States Government as represented by the 2 | Administrator of the National Aeronautics and Space Administration. 3 | All Other Rights Reserved. 4 | -------------------------------------------------------------------------------- /Fortran/._fortranJobScript.job: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Fortran/._fortranJobScript.job -------------------------------------------------------------------------------- /Fortran/munchausen_number.F90: -------------------------------------------------------------------------------- 1 | program munchausen_number 2 | 3 | integer :: i, n 4 | real :: start1, finish1 5 | integer :: power_of_digits(0:9) 6 | 7 | call cpu_time(start1) 8 | 9 | do i = 0, 9 10 | power_of_digits(i) = raisedto(i) 11 | end do 12 | 13 | i = 0 14 | n = 0 15 | 16 | DO WHILE (n < 4) 17 | IF (is_munchausen_number(i)) THEN 18 | n = n + 1 19 | PRINT "('Munchausen Number', 1x, I2, ':', 2x, I10)", n,i 20 | ENDIF 21 | i = i + 1 22 | ENDDO 23 | 24 | call cpu_time(finish1) 25 | print "('Time for Munchausen Numbers:', 2x, f15.10,'s')", finish1 - start1 26 | 27 | contains 28 | 29 | 30 | FUNCTION is_munchausen_number(num) result(answer) 31 | INTEGER, INTENT(in) :: num 32 | LOGICAL :: answer 33 | 34 | INTEGER, DIMENSION(:), ALLOCATABLE :: digs 35 | INTEGER :: num_digits, ix, rem 36 | INTEGER :: sum 37 | 38 | IF (num == 0) THEN 39 | num_digits = 1 40 | ELSE 41 | num_digits = FLOOR(LOG10(REAL(num))+1) 42 | ENDIF 43 | ALLOCATE(digs(num_digits)) 44 | 45 | sum = 0 46 | rem = num 47 | DO ix = 1, num_digits 48 | digs(ix) = rem - (rem/10)*10 ! Take advantage of integer division 49 | rem = rem/10 50 | sum = sum + power_of_digits(digs(ix)) 51 | !sum = sum + raisedto(digs(ix)) 52 | END DO 53 | 54 | DEALLOCATE(digs) 55 | 56 | answer = .FALSE. 57 | IF (sum .EQ. num) answer = .TRUE. 58 | 59 | END FUNCTION is_munchausen_number 60 | 61 | FUNCTION raisedto(n) result(answer) 62 | INTEGER, INTENT(in) :: n 63 | INTEGER :: answer 64 | answer = 0 65 | if (n > 0) answer = n**n 66 | END FUNCTION raisedto 67 | 68 | end program munchausen_number 69 | -------------------------------------------------------------------------------- /Fortran/test_belief_propagation.F90: -------------------------------------------------------------------------------- 1 | program test_belief_propagation 2 | 3 | implicit none 4 | 5 | integer, parameter:: dp=kind(0.d0) 6 | 7 | real(dp) :: r, start, finish, mysum, mynorm 8 | integer :: N, i, j, k 9 | integer, parameter :: dim = 5000 10 | real(dp), allocatable :: A(:,:) 11 | real(dp), allocatable :: x(:), x2(:) 12 | character(len=50) :: arg(1) 13 | 14 | ! Get the dimension from the command line 15 | call getarg(1, arg(1)) 16 | read(arg(1), *) N 17 | 18 | call cpu_time(start) 19 | 20 | ! Allocate and initialize the matrices 21 | !------------------------------------- 22 | allocate(A(dim, dim)) 23 | allocate(x(dim)) 24 | 25 | call srand(86456) 26 | do i = 1, dim 27 | x(i) = 1.0 28 | do j = 1, dim 29 | call random_number(r) 30 | A(i, j) = r 31 | end do 32 | end do 33 | 34 | ! Perform the belief calculations 35 | !-------------------------------- 36 | do k = 1, N 37 | x2 = matmul(A,x) 38 | x(:) = log(x2(:)) 39 | mysum = sum(exp(x(:))) 40 | mynorm = log(mysum) 41 | x(:) = x(:) - mynorm 42 | end do 43 | 44 | call cpu_time(finish) 45 | 46 | print "('Time for Belief Calculations (',i4,'):', 2x, f15.10,'s')", N, finish - start 47 | 48 | end program test_belief_propagation 49 | -------------------------------------------------------------------------------- /Fortran/test_copy_matrix.F90: -------------------------------------------------------------------------------- 1 | ! ********************************************************** 2 | ! Given a nxnx3 matrix A, we want to perform the operations: 3 | ! 4 | ! A[i][j][0] = A[i][j][1] 5 | ! A[i][j][2] = A[i][j][0] 6 | ! A[i][j][1] = A[i][j][2] 7 | ! ********************************************************** 8 | 9 | program test_copy_matrix 10 | 11 | !use timer_module 12 | implicit none 13 | integer, parameter :: dp=kind(0.d0) 14 | 15 | 16 | integer dim1, i, j, l 17 | !real(dp) :: start, finish, tarray(2) 18 | real(dp) :: r, start1, start2, finish1, finish2 19 | real(dp), allocatable :: A(:, :, :) 20 | character(len=30) :: arg(1) 21 | !type(Timer) :: elpTime 22 | 23 | 24 | ! Get the dimension from the command line 25 | call getarg(1, arg(1)) 26 | read(arg(1), *) dim1 27 | 28 | allocate(A(dim1, dim1, 3)) 29 | 30 | ! Loop formulation 31 | !----------------- 32 | 33 | call srand(86456) 34 | do i = 1, dim1 35 | do j = 1, dim1 36 | do l = 1, 3 37 | call random_number(r) 38 | A(i, j, l) = r 39 | end do 40 | end do 41 | end do 42 | 43 | call cpu_time(start1) 44 | !call elpTime%startTimer() 45 | 46 | do j = 1, dim1 47 | do i = 1, dim1 48 | A(i, j, 1) = A(i, j, 2) 49 | A(i, j, 3) = A(i, j, 1) 50 | A(i, j, 2) = A(i, j, 3) 51 | end do 52 | end do 53 | 54 | call cpu_time(finish1) 55 | !call elpTime%stopTimer('Time Matrix Copy - ji loop: ') 56 | print "('Time Matrix Copy - ji loop:', 2x,i5, 2x, f15.10,'s')", dim1, finish1 - start1 57 | 58 | ! Vectorization formulation 59 | !-------------------------- 60 | call srand(86456) 61 | do i = 1, dim1 62 | do j = 1, dim1 63 | do l = 1, 3 64 | call random_number(r) 65 | A(i, j, l) = r 66 | end do 67 | end do 68 | end do 69 | 70 | call cpu_time(start2) 71 | 72 | A(:, :, 1) = A(:, :, 2) 73 | A(:, :, 3) = A(:, :, 1) 74 | A(:, :, 2) = A(:, :, 3) 75 | 76 | call cpu_time(finish2) 77 | print "('Time Matrix Copy - vectorization:', 2x,i5, 2x, f15.10,'s')", dim1, finish2 - start2 78 | 79 | end program test_copy_matrix 80 | -------------------------------------------------------------------------------- /Fortran/test_evaluate_functions.F90: -------------------------------------------------------------------------------- 1 | program test_evaluate_functions 2 | 3 | !use timer_module 4 | implicit none 5 | integer, parameter :: dp=kind(0.d0) 6 | 7 | 8 | integer, parameter :: num_iterations = 10000 9 | integer :: n, i 10 | real(dp) :: start, finish, tarray(2) 11 | real(dp) :: a_min = -1500.00 12 | real(dp) :: a_max = 1500.00 13 | real(dp) :: h 14 | 15 | real(dp), allocatable :: vect1(:) 16 | real(dp), allocatable :: vect2(:) 17 | character(len=30) :: arg(1) 18 | !type(Timer) :: elpTime 19 | 20 | ! Get the dimension from the command line 21 | call getarg(1, arg(1)) 22 | read(arg(1), *) n 23 | 24 | call srand(86456) 25 | call cpu_time(start) 26 | !call elpTime%startTimer() 27 | 28 | allocate(vect1(n)) 29 | allocate(vect2(n)) 30 | h = (a_max - a_min)/(n-1) 31 | 32 | do i = 1, n 33 | vect1(i) = a_min + (i-1)*h 34 | end do 35 | 36 | do i = 1, num_iterations 37 | vect2(:) = DSIN(vect1(:)) 38 | vect1(:) = DASIN(vect2(:)) 39 | vect2(:) = DCOS(vect1(:)) 40 | vect1(:) = DACOS(vect2(:)) 41 | vect2(:) = DTAN(vect1(:)) 42 | vect1(:) = DATAN(vect2(:)) 43 | end do 44 | 45 | call cpu_time(finish) 46 | !call elpTime%stopTimer('Time Matrix Copy - ji loop: ') 47 | print "('Time Evaluate Function:', 2x,i7, 2x, f15.10,'s')", n, finish - start 48 | 49 | end program test_evaluate_functions 50 | -------------------------------------------------------------------------------- /Fortran/test_fibonacci.F90: -------------------------------------------------------------------------------- 1 | program test_fibonacci 2 | 3 | implicit none 4 | 5 | integer, parameter :: dp=kind(0.d0) 6 | 7 | real(dp) :: start, finish 8 | integer m, n1, n2 9 | character(len=50) :: arg(1) 10 | 11 | ! Get the dimension from the command line 12 | call getarg(1,arg(1)) 13 | read(arg(1), * ) m 14 | 15 | ! Calculation with loop 16 | !---------------------- 17 | call cpu_time(start) 18 | n2 = fibonacci_iterative(m) 19 | call cpu_time(finish) 20 | print "('Iterative Fibonacci (',i2,'):', 2x, f15.10,'s')", m, finish - start 21 | 22 | ! Calculation with recursive function 23 | !------------------------------------ 24 | call cpu_time(start) 25 | n1 = fibonacci_recursive(m) 26 | call cpu_time(finish) 27 | print "('Recursive Fibonacci (',i2,'):', 2x, f15.10,'s')", m, finish - start 28 | 29 | !------------------------------------------------------------------------------ 30 | contains 31 | !------------------------------------------------------------------------------ 32 | recursive function fibonacci_recursive(n) result(fib) 33 | integer, intent(in) :: n 34 | integer :: fib 35 | 36 | select case (n) 37 | case (:0); fib = 0 38 | case (1); fib = 1 39 | case default; fib = fibonacci_recursive(n-1) + fibonacci_recursive(n-2) 40 | end select 41 | end function fibonacci_recursive 42 | 43 | function fibonacci_iterative(n) result(fib) 44 | integer, intent(in) :: n 45 | integer, parameter :: fib0 = 0, fib1 = 1 46 | integer :: fib, back1, back2, i 47 | 48 | select case (n) 49 | case (:0); fib = fib0 50 | case (1); fib = fib1 51 | case default 52 | fib = fib1 53 | back1 = fib0 54 | do i = 2, n 55 | back2 = back1 56 | back1 = fib 57 | fib = back1 + back2 58 | end do 59 | end select 60 | end function fibonacci_iterative 61 | 62 | end program test_fibonacci 63 | -------------------------------------------------------------------------------- /Fortran/test_laplace_jacobi_4_vectorized.F90: -------------------------------------------------------------------------------- 1 | !---------------------------------------------------------------------- 2 | ! Numerical solution of the 2D Laplce equation: 3 | ! 4 | ! u + u = 0 5 | ! xx yy 6 | !---------------------------------------------------------------------- 7 | program test_laplace_jacobi_4_vectorized 8 | 9 | implicit none 10 | integer, parameter :: dp=kind(0.d0) 11 | 12 | real(dp), parameter :: pi=3.141592653589793 13 | real(dp), parameter :: eps = 1.0d-6 14 | integer, parameter :: max_sweep = 1000000 15 | integer :: n, count, i 16 | real(dp), allocatable :: u(:, :) 17 | real(dp), allocatable :: v(:, :) 18 | real(dp), allocatable :: x(:) 19 | real(dp) :: error, start, finish 20 | character(len=30) :: arg(1) 21 | 22 | call cpu_time(start) 23 | ! Get the dimension from the command line 24 | call getarg(1, arg(1)) 25 | read(arg(1), *) n 26 | 27 | ! Variable allocation and initial conditions 28 | allocate(u(n, n)) 29 | allocate(v(n, n)) 30 | allocate(x(n)) 31 | 32 | do i = 1, n 33 | x(:) = 1.0*(i-1)/n 34 | end do 35 | 36 | u(:, :) = 0.0 37 | u(:, 1) = sin(pi*x(:)) 38 | u(:, n) = sin(pi*x(:))*exp(-pi) 39 | 40 | error = 2 41 | count = 0 42 | 43 | ! Jacobi iterations 44 | do while ( (count < max_sweep) .and. (error > eps)) 45 | count = count + 1 46 | v(:, :) = u(:, :) 47 | u(2:n-1, 2:n-1) = ((v(1:n-2, 2:n-1) + v(3:n, 2:n-1) & 48 | & + v(2:n-1, 1:n-2) + v(2:n-1, 3:n))*4.0 & 49 | & + v(1:n-2, 1:n-2) + v(3:n, 1:n-2) & 50 | & + v(1:n-2, 3:n) + v(3:n, 3:n))/20.0 51 | error = normError(u-v) 52 | end do 53 | 54 | call cpu_time(finish) 55 | 56 | print*, "Fortran Solution of Laplace Equation: (vectorization)", n 57 | print*, " Number of iterations: ", count 58 | print*, " Error: ", error 59 | print '(" Time: ",f6.3," seconds.")', finish-start 60 | 61 | !------------------------------------------------------------------------------ 62 | contains 63 | !------------------------------------------------------------------------------ 64 | function normError(w) result(norm2) 65 | real(dp) :: w(n, n) 66 | integer :: i, j 67 | real(dp) :: norm2, err 68 | err = 0.00 69 | do j=2, n-1 70 | do i=2, n-1 71 | err = err + w(i, j)*w(i, j) 72 | end do 73 | end do 74 | 75 | norm2 = sqrt(err) 76 | end function normError 77 | 78 | end program test_laplace_jacobi_4_vectorized 79 | -------------------------------------------------------------------------------- /Fortran/test_look_and_say.F90: -------------------------------------------------------------------------------- 1 | program test_look_and_say 2 | 3 | implicit none 4 | integer, parameter :: dp=kind(0.d0) 5 | integer, parameter :: stringlen=700 6 | 7 | integer :: i, N 8 | character(len=stringlen) :: t, r 9 | real(dp) start, finish 10 | character(len=50) :: arg(1) 11 | 12 | 13 | ! Get the dimension from the command line 14 | call getarg(1, arg(1)) 15 | read(arg(1), *) N 16 | 17 | call cpu_time(start) 18 | 19 | call look_and_say("1223334444", r, N) 20 | 21 | call cpu_time(finish) 22 | 23 | print "('Time for Look and Say (',i4,'):', 2x, f15.10,'s')", N, finish - start 24 | 25 | !------------------------------------------------------------------------------ 26 | contains 27 | !------------------------------------------------------------------------------ 28 | subroutine look_and_say(startseq, lastseq, n) 29 | integer, intent(in) :: n ! number of iterations 30 | character(len=*), intent(in) :: startseq ! starting sequence 31 | character(len=*), intent(out) :: lastseq ! ending sequence 32 | 33 | integer :: i, c, iter, it 34 | character(len=1) :: x 35 | character(len=2) :: d 36 | character(len=stringlen) :: currentseq 37 | 38 | currentseq = startseq 39 | if (n < 2) then 40 | lastseq = startseq 41 | else 42 | do it = 2, n 43 | lastseq = "" 44 | c = 1 45 | x = currentseq(1:1) 46 | do i = 2, len(trim(currentseq)) 47 | if ( x == currentseq(i:i) ) then 48 | c = c + 1 49 | else 50 | write(d, "(I2)") c 51 | lastseq = trim(lastseq) // trim(adjustl(d)) // trim(x) 52 | c = 1 53 | x = currentseq(i:i) 54 | end if 55 | end do 56 | write(d, "(I2)") c 57 | lastseq = trim(lastseq) // trim(adjustl(d)) // trim(x) 58 | currentseq = lastseq 59 | end do 60 | end if 61 | end subroutine look_and_say 62 | 63 | end program test_look_and_say 64 | -------------------------------------------------------------------------------- /Fortran/test_matrix_multiplication.F90: -------------------------------------------------------------------------------- 1 | 2 | program test_matrix_multiplication 3 | 4 | implicit none 5 | integer, parameter :: dp=kind(0.d0) 6 | 7 | real(dp) :: r, start, finish 8 | integer :: dim1, dim2, dim3, i, j, k 9 | real(dp), allocatable :: A(:, :) 10 | real(dp), allocatable :: B(:, :) 11 | real(dp), allocatable :: C(:, :) 12 | 13 | integer, parameter :: n = 3 14 | character(len=50) :: arg(n) 15 | 16 | ! Get the dimension from the command line 17 | do i =1, n 18 | call getarg(i,arg(i)) 19 | end do 20 | read(arg(1), *) dim1 21 | read(arg(2), *) dim2 22 | read(arg(3), *) dim3 23 | 24 | write(*, 110) 'Perform matrix multiplication:', & 25 | ' C(', dim1, ',', dim3, ') = A(', dim1, ',', dim2, ') x B(', dim2, ',', dim3, ')' 26 | 110 format(a30, a3, i4, a1, i4, a6, i4, a1, i4, a6, i4, a1, i4, a1) 27 | 28 | ! Allocate the three matrices 29 | allocate(A(dim1, dim2)) 30 | allocate(B(dim2, dim3)) 31 | allocate(C(dim1, dim3)) 32 | 33 | ! Initialize the matrices A & B 34 | call srand(86456) 35 | do i = 1, dim1 36 | do j = 1, dim2 37 | call random_number(r) 38 | A(i, j) = r 39 | end do 40 | end do 41 | do i = 1, dim2 42 | do j = 1, dim3 43 | call random_number(r) 44 | B(i, j) = r 45 | end do 46 | end do 47 | 48 | ! Perform the matrix multiplication using loops 49 | call cpu_time(start) 50 | do j = 1, dim3 51 | do i = 1, dim1 52 | C(i, j) = 0. 53 | do k = 1, dim2 54 | C(i, j) = C(i, j) + A(i, k)*B(k, j) 55 | end do 56 | end do 57 | end do 58 | call cpu_time(finish) 59 | write(*, 100)' ---> Loops: ', finish - start, ' s' 60 | 61 | ! Perform the matrix multiplication the intrinsic 62 | ! function matmul 63 | call cpu_time(start) 64 | C = matmul(A, B) 65 | call cpu_time(finish) 66 | 67 | write(*, 100) ' ---> Function matmul: ', finish - start, ' s' 68 | 100 format(a26, f10.4, a2) 69 | 70 | end program test_matrix_multiplication 71 | -------------------------------------------------------------------------------- /Fortran/test_matrix_multiplication_DGEMM.F90: -------------------------------------------------------------------------------- 1 | ! ********************************************************** 2 | ! Given two nxn matrices A and B, we perform: 3 | ! C = A x B 4 | ! ********************************************************** 5 | 6 | program test_matrix_multiplication_DGEMM 7 | 8 | implicit none 9 | integer, parameter :: dp=kind(0.d0) 10 | 11 | integer iseed /3/ 12 | real(dp) start, finish, r, alpha, beta 13 | integer :: n, i, j, lda, ldb, ldc 14 | real(dp), allocatable :: A(:, :), B(:, :), C(:, :) 15 | 16 | character(len=30) :: arg(1) 17 | 18 | ! Get the dimension from the command line 19 | call getarg(1, arg(1)) 20 | read(arg(1), *) n 21 | 22 | write(*, 110) 'Perform matrix multiplication:', & 23 | ' C(', n, ',', n, ') = A(', n, ',', n, ') x B(', n, ',', n, ')' 24 | 110 format(a30, a3, i4, a1, i4, a6, i4, a1, i4, a6, i4, a1, i4, a1) 25 | 26 | alpha = 1.0 27 | beta = 0.0 28 | lda = n 29 | ldb = n 30 | ldc = n 31 | 32 | ! Allocate and initialize the matrices 33 | allocate(A(n, n)) 34 | allocate(B(n, n)) 35 | allocate(C(n, n)) 36 | 37 | call srand(86456) 38 | do i = 1, n 39 | do j = 1, n 40 | call random_number(r) 41 | A(i, j) = r 42 | call random_number(r) 43 | B(i, j) = r 44 | end do 45 | end do 46 | 47 | ! Perform the matrix multiplication 48 | C = 0.0 49 | call cpu_time(start) 50 | 51 | call dgemm("N", "N", n, n, n, alpha, A, lda, B, ldb, beta, C, ldc) 52 | 53 | call cpu_time(finish) 54 | 55 | write(*, 100) ' ---> Function DGEMM: ', finish - start, ' s' 56 | 100 format(a26, f10.4, a2) 57 | 58 | end program test_matrix_multiplication_DGEMM 59 | 60 | 61 | -------------------------------------------------------------------------------- /Fortran/test_munchausen_number.F90: -------------------------------------------------------------------------------- 1 | program test_munchausen_number 2 | 3 | implicit none 4 | integer, parameter :: dp=kind(0.d0) 5 | 6 | integer :: i, n 7 | real(dp) :: start1, finish1 8 | integer :: power_of_digits(0:9) 9 | 10 | call cpu_time(start1) 11 | 12 | do i = 0, 9 13 | power_of_digits(i) = raisedto(i) 14 | end do 15 | 16 | i = 0 17 | n = 0 18 | 19 | do while (n < 4) 20 | if (is_munchausen_number(i)) then 21 | n = n + 1 22 | print "('Munchausen Number', 1x, I2, ':', 2x, I10)", n,i 23 | end if 24 | i = i + 1 25 | end do 26 | 27 | call cpu_time(finish1) 28 | print "('Time for Munchausen Numbers:', 2x, f15.10,'s')", finish1 - start1 29 | 30 | !------------------------------------------------------------------------------ 31 | contains 32 | !------------------------------------------------------------------------------ 33 | function is_munchausen_number(num) result(answer) 34 | integer, intent(in) :: num 35 | logical :: answer 36 | 37 | integer, dimension(:), allocatable :: digs 38 | integer :: num_digits, ix, rem 39 | integer :: sum 40 | 41 | if (num == 0) then 42 | num_digits = 1 43 | else 44 | num_digits = floor(LOG10(real(num))+1) 45 | end if 46 | allocate(digs(num_digits)) 47 | 48 | sum = 0 49 | rem = num 50 | do ix = 1, num_digits 51 | digs(ix) = rem - (rem/10)*10 ! Take advantage of integer division 52 | rem = rem/10 53 | sum = sum + power_of_digits(digs(ix)) 54 | !sum = sum + raisedto(digs(ix)) 55 | end do 56 | 57 | deallocate(digs) 58 | 59 | answer = .FALSE. 60 | if (sum .EQ. num) answer = .TRUE. 61 | end function 62 | 63 | function raisedto(n) result(answer) 64 | integer, intent(in) :: n 65 | integer :: answer 66 | answer = 0 67 | if (n > 0) answer = n**n 68 | end function raisedto 69 | 70 | end program test_munchausen_number 71 | -------------------------------------------------------------------------------- /Fortran/test_pernicious_numbers.F90: -------------------------------------------------------------------------------- 1 | ! ************************************************************* 2 | ! http://www.rosettacode.org/wiki/Pernicious_numbers 3 | ! 4 | ! ************************************************************* 5 | program pernicious_numbers 6 | implicit none 7 | 8 | integer, parameter :: dp=kind(0.d0) 9 | 10 | integer :: i, n 11 | integer :: max_number 12 | real(dp) :: r, start1, start2, finish1, finish2 13 | character(len=30) :: arg(1) 14 | 15 | ! Get the dimension from the command line 16 | call getarg(1, arg(1)) 17 | read(arg(1), *) max_number 18 | 19 | call cpu_time(start1) 20 | i = 1 21 | n = 0 22 | do 23 | if (is_prime_number(get_number_of_ones(i))) then 24 | !if ((n == 0) .OR. (n == max_number-1)) write(*, "(i0, 1x)", advance = "no") i 25 | n = n + 1 26 | if (n == max_number) exit 27 | end if 28 | i = i + 1 29 | end do 30 | call cpu_time(finish1) 31 | print "('Pernicious number:', 2x,i10, 2x, f15.10,'s')", i, finish1 - start1 32 | 33 | !----------------------------------------------------------------- 34 | contains 35 | !----------------------------------------------------------------- 36 | 37 | function get_number_of_ones(x) result(number_of_ones) 38 | integer :: number_of_ones 39 | integer, intent(in) :: x 40 | integer :: i 41 | 42 | number_of_ones = 0 43 | !do i = 0, 31 44 | do i = 0, BIT_SIZE(x)-1 45 | if (BTEST(x, i)) number_of_ones = number_of_ones + 1 46 | end do 47 | 48 | end function get_number_of_ones 49 | 50 | function is_prime_number(number) result(iamprime) 51 | integer, intent(in) :: number 52 | logical :: iamprime 53 | integer :: i 54 | 55 | if(number == 2) then 56 | iamprime = .true. 57 | else if(number < 2 .or. mod(number,2) == 0) then 58 | iamprime = .false. 59 | else 60 | iamprime = .true. 61 | do i = 3, int(sqrt(real(number))), 2 62 | if(mod(number,i) == 0) then 63 | iamprime = .false. 64 | exit 65 | end if 66 | end do 67 | end if 68 | end function is_prime_number 69 | end program pernicious_numbers 70 | -------------------------------------------------------------------------------- /IDL/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/IDL/.DS_Store -------------------------------------------------------------------------------- /IDL/._.DS_Store: -------------------------------------------------------------------------------- 1 | Mac OS X  2Fx @ATTRxx -------------------------------------------------------------------------------- /IDL/brm_gau_leg_54.pro: -------------------------------------------------------------------------------- 1 | ;+ 2 | ; PROJECT: 3 | ; HESSI 4 | ; 5 | ; NAME: 6 | ; Brm_GauLeg54 7 | ; 8 | ; PURPOSE: 9 | ; Returns arrays x and w, containing the abscissas and weights of the 10 | ; Gauss-Legendre n-point quadrature formula. 11 | ; 12 | ; CATEGORY: 13 | ; HESSI, Spectra, Modeling 14 | ; 15 | ; CALLING SEQUENCE: 16 | ; Brm_GauLeg54, x1, x2, n, x, w 17 | ; 18 | ; CALLS: 19 | ; none 20 | ; 21 | ; INPUTS: 22 | ; 23 | ; x1 - Array containing lower limits of integration. 24 | ; 25 | ; x2 - Upper limit(s) of integration. This input may be either a 26 | ; scalar, or an array corresponding to x1. 27 | ; 28 | ; n - Number of points evaluated. 29 | ; 30 | ; 31 | ; OPTIONAL INPUTS: 32 | ; none 33 | ; 34 | ; OUTPUTS: 35 | ; 36 | ; x - Two-dimensional array containing the abscissas of the Gauss- 37 | ; Legendre n-point quadrature formula. Each column of this array 38 | ; corresponds to an element of the input array x1. 39 | ; 40 | ; w - Two-dimensional array containing the weights of the Gauss- 41 | ; Legendre n-point quadrature formula. Each column of this array 42 | ; corresponds to an element of the input array x1. 43 | ; 44 | ; 45 | ; OPTIONAL OUTPUTS: 46 | ; none 47 | ; 48 | ; KEYWORDS: 49 | ; none 50 | ; 51 | ; COMMON BLOCKS: 52 | ; none 53 | ; 54 | ; SIDE EFFECTS: 55 | ; 56 | ; 57 | ; RESTRICTIONS: 58 | ; 59 | ; 60 | ; PROCEDURE: 61 | ; This procedure is based upon the subroutine in "Numerical Recipes in 62 | ; Fortran 77," Second Edition, Cambridge University Press, p. 145. This 63 | ; procedure may be used only with IDL Version 5.4 or later. 64 | ; 65 | ; MODIFICATION HISTORY: 66 | ; Version 1, holman@stars.gsfc.nasa.gov, 23 July 2001 67 | ; IDL version: Sally House, summer intern 68 | ; Documentation for the Fortran Version of this code can be found at 69 | ; http://hesperia.gsfc.nasa.gov/hessi/modelware.htm 70 | ; 71 | ;- 72 | 73 | Pro brm_gau_leg_54, x1, x2, n, x, w 74 | 75 | eps = 3.d-14 76 | 77 | m = (n+1)/2 78 | 79 | xm = 0.5d0*(x2+x1) 80 | xl = 0.5d0*(x2-x1) 81 | 82 | FOR i = 1, m DO BEGIN 83 | 84 | z = Cos(!dpi*(i-0.25d0)/(n+0.5d0)) 85 | 86 | noconv: 87 | 88 | p1 = Legendre(z, n, /Double) 89 | p2 = Legendre(z, n-1, /Double) 90 | 91 | pp = n*(z*p1-p2)/(z^2-1.d0) 92 | 93 | z1 = z 94 | z = z1-p1/pp 95 | 96 | IF (Abs(z-z1) GT eps) THEN GOTO, noconv 97 | 98 | x(*,i-1) = xm-xl*z 99 | x(*,n-i) = xm+xl*z 100 | w(*,i-1) = 2.d0*xl/((1.d0-z^2)*pp^2) 101 | w(*,n-i) = w(*,i-1) 102 | 103 | ENDFOR 104 | 105 | END 106 | -------------------------------------------------------------------------------- /IDL/idl_job_script: -------------------------------------------------------------------------------- 1 | #! /bin/csh -f 2 | #SBATCH --time=07:30:00 3 | #SBATCH --job-name=idl 4 | #SBATCH --ntasks=40 5 | #SBATCH --constraint=sky 6 | #SBATCH -A j1008 7 | #SBATCH --mail-type=BEGIN 8 | #SBATCH --mail-type=END 9 | #SBATCH -o IDL2021log-%j.out 10 | 11 | ################## 12 | # Load the modules 13 | ################## 14 | 15 | source /usr/share/modules/init/csh 16 | module purge 17 | module load idl/8.5 18 | 19 | limit vmemoryuse unlimited 20 | limit stacksize unlimited 21 | 22 | idl run_all_scripts 23 | 24 | -------------------------------------------------------------------------------- /IDL/run_all_scripts.pro: -------------------------------------------------------------------------------- 1 | PRINT, 'Job started' 2 | 3 | test_copy_matrix, 5000 4 | test_copy_matrix, 7000 5 | test_copy_matrix, 9000 6 | 7 | test_look_and_say, 40 8 | test_look_and_say, 45 9 | test_look_and_say, 48 10 | 11 | test_fibonacci, 25 12 | test_fibonacci, 35 13 | test_fibonacci, 45 14 | 15 | test_matrix_multiplication, 1500 16 | test_matrix_multiplication, 1750 17 | test_matrix_multiplication, 2000 18 | 19 | test_belief_propagation, 250 20 | test_belief_propagation, 500 21 | test_belief_propagation, 1000 22 | 23 | test_markov_chain, 5000 24 | test_markov_chain, 10000 25 | test_markov_chain, 15000 26 | 27 | test_compute_fft, 10000 28 | test_compute_fft, 15000 29 | test_compute_fft, 20000 30 | 31 | test_laplace_jacobi_4, 100 32 | test_laplace_jacobi_4, 150 33 | test_laplace_jacobi_4, 200 34 | 35 | test_gauss_legendre_quadrature, 50 36 | test_gauss_legendre_quadrature, 75 37 | test_gauss_legendre_quadrature, 100 38 | 39 | test_evaluate_functions, 80000 40 | test_evaluate_functions, 90000 41 | test_evaluate_functions, 100000 42 | 43 | test_pernicious_numbers, 100000 44 | 45 | test_munchausen_number 46 | 47 | 48 | ;test_time_series_aoa 49 | 50 | PRINT, 'Job complete' 51 | -------------------------------------------------------------------------------- /IDL/test_belief_propagation.pro: -------------------------------------------------------------------------------- 1 | ; 2 | ; .run beliefPropagation 3 | ; beliefPropagation, nx 4 | ; 5 | PRO test_belief_propagation, N 6 | 7 | PRINT, '----------------------------' 8 | PRINT, 'Belief calculations: ', N 9 | PRINT, '----------------------------' 10 | PRINT, ' ' 11 | 12 | time0 = SYSTIME(/SECONDS) 13 | 14 | random_value = RANDOMN(Seed) 15 | 16 | dim = 5000 17 | 18 | A = RANDOMN(Seed, dim,dim) 19 | x = FLTARR(dim) 20 | 21 | x[0:dim-1] = 1.0 22 | 23 | FOR i = 1,N DO BEGIN 24 | x = ALOG10(A#EXP(x)) 25 | x -= ALOG10(TOTAL(EXP(x))) 26 | ENDFOR 27 | 28 | time1 = SYSTIME(/SECONDS) - time0 29 | PRINT, 'Elapsed time: ', time1 30 | 31 | RETURN 32 | END 33 | -------------------------------------------------------------------------------- /IDL/test_compute_fft.pro: -------------------------------------------------------------------------------- 1 | 2 | ; ********************************************************** 3 | ; ********************************************************** 4 | 5 | PRO test_compute_fft, n 6 | 7 | PRINT, '----------------------------' 8 | PRINT, 'FFTs: ', n 9 | PRINT, '----------------------------' 10 | PRINT, ' ' 11 | 12 | time0 = SYSTIME(/SECONDS) 13 | 14 | seed1 = !NULL 15 | random_value_1 = RANDOMU(seed1) 16 | seed2 = !NULL 17 | random_value_2 = RANDOMN(seed2) 18 | 19 | ;A = RANDOMN(seed, n,n) 20 | ;B = RANDOMN(seed, n,n) 21 | mat = COMPLEX(RANDOMN(seed1, n,n), RANDOMN(seed2, n,n)) 22 | 23 | result = FFT(mat) 24 | result = ABS(result) 25 | 26 | time1 = SYSTIME(/SECONDS) - time0 27 | PRINT, 'Elapsed time: ', time1 28 | 29 | RETURN 30 | 31 | END 32 | -------------------------------------------------------------------------------- /IDL/test_copy_matrix.pro: -------------------------------------------------------------------------------- 1 | ; ********************************************************** 2 | ; Given a nxnx3 matrix A, we want to perform the operations: 3 | ; 4 | ; A[i][j][0] = A[i][j][1] 5 | ; A[i][j][2] = A[i][j][0] 6 | ; A[i][j][1] = A[i][j][2] 7 | ; ********************************************************** 8 | 9 | PRO test_copy_matrix, nx 10 | 11 | 12 | PRINT, "-------------------------" 13 | PRINT, "Copy of matrix (ji loop)" 14 | PRINT, "-------------------------" 15 | 16 | random_value = RANDOMN(Seed) 17 | A = RANDOMN(Seed, nx,nx, 3) 18 | 19 | time0 = SYSTIME(/SECONDS) 20 | FOR j = 0,nx-1 DO BEGIN 21 | FOR i = 0,nx-1 DO BEGIN 22 | A[i,j,0] = A[i,j,1] 23 | A[i,j,2] = A[i,j,0] 24 | A[i,j,1] = A[i,j,2] 25 | ENDFOR 26 | ENDFOR 27 | 28 | time_ji_loop = SYSTIME(/SECONDS) - time0 29 | print, 'Time for ji Loop: ', time_ji_loop 30 | 31 | PRINT, " " 32 | 33 | PRINT, "--------------------------" 34 | PRINT, "Vectorized Copy of matrix" 35 | PRINT, "--------------------------" 36 | 37 | random_value = RANDOMN(Seed) 38 | A = RANDOMN(Seed, nx,nx, 3) 39 | 40 | time0 = SYSTIME(/SECONDS) 41 | 42 | A[*,*,0] = A[*,*,1] 43 | A[*,*,2] = A[*,*,0] 44 | A[*,*,1] = A[*,*,2] 45 | 46 | time_vec = SYSTIME(/SECONDS) - time0 47 | PRINT, 'Time for vectorization: ', time_vec 48 | 49 | PRINT, " " 50 | 51 | END 52 | -------------------------------------------------------------------------------- /IDL/test_evaluate_functions.pro: -------------------------------------------------------------------------------- 1 | ;---------------------------------------------------------------------- 2 | ;---------------------------------------------------------------------- 3 | 4 | FUNCTION FUNCTION_ARG, x, M, func 5 | 6 | FOR i = 1, M DO BEGIN 7 | t = CALL_FUNCTION(func, x) 8 | ENDFOR 9 | 10 | RETURN, t 11 | END 12 | 13 | ; Main program 14 | PRO test_evaluate_functions, n 15 | PRINT, "------------------------------------------------" 16 | PRINT, "Compute values: ", n 17 | PRINT, "------------------------------------------------" 18 | 19 | time0 = SYSTIME(/SECONDS) 20 | M = 10000 21 | a = -1500.00 22 | b = 1500.00 23 | h = (b-a)/(n-1) 24 | x = INDGEN(n)*h + a 25 | 26 | FOR i = 1, M DO BEGIN 27 | y = SIN(x) 28 | x = ASIN(y) 29 | y = COS(x) 30 | x = ACOS(y) 31 | y = TAN(x) 32 | x = ATAN(y) 33 | ENDFOR 34 | 35 | time1 = SYSTIME(/SECONDS) - time0 36 | 37 | PRINT, ' Elapsed time: ', time1 38 | PRINT, " " 39 | 40 | RETURN 41 | END 42 | -------------------------------------------------------------------------------- /IDL/test_fibonacci.pro: -------------------------------------------------------------------------------- 1 | 2 | FUNCTION recursive_fibonacci,n 3 | IF n lt 3 THEN RETURN,1L ELSE RETURN, recursive_fibonacci(n-1)+recursive_fibonacci(n-2) 4 | END 5 | 6 | FUNCTION iterative_fibonacci,n 7 | psum = (csum = 1uL) 8 | IF n lt 3 THEN RETURN,csum 9 | FOR i = 3,n DO BEGIN 10 | nsum = psum + csum 11 | psum = csum 12 | csum = nsum 13 | ENDFOR 14 | RETURN,nsum 15 | END 16 | 17 | PRO test_fibonacci, n 18 | 19 | time0 = SYSTIME(/SECONDS) 20 | n1 = iterative_fibonacci(n) 21 | time1 = SYSTIME(/SECONDS) - time0 22 | PRINT, 'Iterative Fibonacci (',n,'): ', time1, n1 23 | 24 | time0 = SYSTIME(/SECONDS) 25 | n2 = recursive_fibonacci(n) 26 | time1 = SYSTIME(/SECONDS) - time0 27 | PRINT, 'Recursive Fibonacci (',n,'): ', time1, n2 28 | 29 | RETURN 30 | END 31 | -------------------------------------------------------------------------------- /IDL/test_gauss_legendre_quadrature.pro: -------------------------------------------------------------------------------- 1 | PRO test_gauss_legendre_quadrature, n 2 | 3 | 4 | PRINT, "-------------------------" 5 | PRINT, "Gauss Legendre Quadrature", n 6 | PRINT, "-------------------------" 7 | 8 | time_beg = SYSTIME(/SECONDS) 9 | 10 | x1 = -3.0 11 | x2 = 3.0 12 | x = FLTARR(1,n) 13 | w = FLTARR(1,n) 14 | 15 | brm_gau_leg_54, x1, x2, n, x, w 16 | 17 | quad = TOTAL(w*exp(x)) 18 | 19 | time_end = SYSTIME(/SECONDS) - time_beg 20 | PRINT, 'Time for Gauss Legendre Quadrature: ', time_end 21 | 22 | PRINT, " " 23 | 24 | END 25 | -------------------------------------------------------------------------------- /IDL/test_look_and_say.pro: -------------------------------------------------------------------------------- 1 | 2 | ; Construct the look and say sequence of order num and 3 | ; starting sequence, start_seq (string). 4 | 5 | PRO test_look_and_say, num 6 | time0 = SYSTIME(/SECONDS) 7 | 8 | start_seq = '1223334444' 9 | i = 0 10 | 11 | WHILE (i LT num) DO BEGIN 12 | IF (i EQ 0) THEN BEGIN 13 | cur_seq = start_seq 14 | ENDIF ELSE BEGIN 15 | count = 1 16 | temp_series = '' 17 | FOR j = 1, STRLEN(cur_seq)-1 DO BEGIN 18 | IF (STRMID(cur_seq, j, 1) EQ STRMID(cur_seq, j-1, 1)) THEN BEGIN 19 | count = count + 1 20 | ENDIF ELSE BEGIN 21 | temp_series = temp_series + STRTRIM(count,1) + STRMID(cur_seq, j-1, 1) 22 | count = 1 23 | ENDELSE 24 | ENDFOR 25 | temp_series = temp_series + STRTRIM(count,1) + STRMID(cur_seq, STRLEN(cur_seq)-1, 1) 26 | cur_seq = temp_series 27 | ENDELSE 28 | i = i + 1 29 | ENDWHILE 30 | 31 | time1 = SYSTIME(/SECONDS) - time0 32 | PRINT, 'Look and Say Sequence (',num,'): ', time1 33 | ;print, cur_seq 34 | END 35 | -------------------------------------------------------------------------------- /IDL/test_markov_chain.pro: -------------------------------------------------------------------------------- 1 | 2 | PRO test_markov_chain, N 3 | 4 | PRINT, '----------------------------' 5 | PRINT, 'Markov Chain calculations: ', N 6 | PRINT, '----------------------------' 7 | PRINT, ' ' 8 | 9 | time0 = SYSTIME(/SECONDS) 10 | 11 | random_value_N = RANDOMN(seedN) 12 | random_value_U = RANDOMN(seedU) 13 | 14 | x = FLTARR(2) 15 | x2= FLTARR(2) 16 | 17 | x[0:1] = 0.0 18 | 19 | p = EXP(SIN(5.0*x[0]) - x[0]*x[0] - x[1]*x[1]) 20 | ;p = FF(x) 21 | 22 | FOR i = 1,N DO BEGIN 23 | x2 = x + 0.01*RANDOMN(seedN, 2) 24 | p2 = EXP(SIN(5.0*x2[0]) - x2[0]*x2[0] - x2[1]*x2[1]) 25 | ;p2 = FF(x2) 26 | IF (RANDOMU(seedU, 1) < (p2/p)) THEN BEGIN 27 | x = x2 28 | p = p2 29 | ENDIF 30 | ENDFOR 31 | 32 | time1 = SYSTIME(/SECONDS) - time0 33 | PRINT, 'Elapsed time: ', time1 34 | 35 | RETURN 36 | END 37 | -------------------------------------------------------------------------------- /IDL/test_matrix_multiplication.pro: -------------------------------------------------------------------------------- 1 | ; ********************************************************** 2 | ; Given two nxn matrices A and B, we perform: 3 | ; C = A x B 4 | ; ********************************************************** 5 | ; 6 | PRO test_matrix_multiplication, nx 7 | 8 | PRINT, '----------------------------' 9 | PRINT, 'Matrix dimensions: ', nx 10 | PRINT, '----------------------------' 11 | PRINT, ' ' 12 | 13 | random_value = RANDOMN(seed) 14 | 15 | A = RANDOMN(seed, nx,nx) 16 | B = RANDOMN(seed, nx,nx) 17 | C = FLTARR(nx,nx) 18 | 19 | PRINT, 'multiply two matrices' 20 | 21 | time0 = SYSTIME(/SECONDS) 22 | 23 | C = A#B 24 | 25 | time1 = SYSTIME(/SECONDS) - time0 26 | PRINT, 'Elapsed time: ', time1 27 | 28 | RETURN 29 | END 30 | -------------------------------------------------------------------------------- /IDL/test_munchausen_number.pro: -------------------------------------------------------------------------------- 1 | 2 | FUNCTION raised_to, x 3 | IF x eq 0 THEN RETURN,0 ELSE RETURN, LONG64(x^x) 4 | END 5 | 6 | FUNCTION sum_digit_power, i 7 | A = STRTRIM(STRING(i),1) 8 | my_sum = LONG64(0) 9 | FOR k=0, A.STRLEN()-1 DO BEGIN 10 | my_sum = my_sum + raised_to(FIX(A.CharAt(k))) 11 | ;PRINT, k, my_sum 12 | ENDFOR 13 | RETURN, my_sum 14 | END 15 | 16 | PRO test_munchausen_number 17 | 18 | time0 = SYSTIME(/SECONDS) 19 | num = 0 20 | i = LONG64(0) 21 | WHILE (num LE 4) DO BEGIN 22 | IF (i EQ sum_digit_power(i)) THEN BEGIN 23 | num++ 24 | PRINT, 'The Munchausen number', num, ' is: ', i 25 | ENDIF 26 | 27 | ;IF ((i MOD 1000000LL) EQ 0) THEN print, 'Number: ', i 28 | i++ 29 | ENDWHILE 30 | time1 = SYSTIME(/SECONDS) - time0 31 | PRINT, 'Time for Munchausen numbers: ', time1 32 | 33 | RETURN 34 | END 35 | -------------------------------------------------------------------------------- /IDL/test_pernicious_numbers.pro: -------------------------------------------------------------------------------- 1 | 2 | FUNCTION count_ones,n 3 | ; ------------------------------------------------------------- 4 | ; Count the number of 1s in a binary number 5 | ; 1. Convert the binary number into a string 6 | ; 2. Extract all the 0s from the string and get a string (with empty speces) of 1s 7 | ; 3. Join the string by removing empty spaces. 8 | ; 3. Count the length of the new string. 9 | ; ------------------------------------------------------------- 10 | RETURN, STRLEN(STRJOIN(STRSPLIT(STRING(n), '0', /EXTRACT))) 11 | END 12 | 13 | ; Use the LAMBDA function to determine if a number is prime 14 | ; https://www.l3harrisgeospatial.com/Support/Maintenance-Detail/ArtMID/13350/ArticleID/15792/Whats-New-in-IDL-84 15 | ; isprime = LAMBDA(n:n le 3 || MIN(n mod [2:FIX(SQRT(n))])) 16 | 17 | FUNCTION is_prime_number, m 18 | ; Determine if a number is prime (1) or not (0). 19 | IF (m LT 2) THEN BEGIN 20 | num = 0 21 | ENDIF ELSE BEGIN 22 | isprime = LAMBDA(n:n le 3 || MIN(n mod [2:FIX(SQRT(n))])) 23 | num = m.Map(isprime) 24 | ENDELSE 25 | RETURN, num 26 | END 27 | 28 | PRO test_pernicious_numbers, max_num 29 | 30 | time0 = SYSTIME(/SECONDS) 31 | 32 | i = 1L 33 | num_pernicious = 0L 34 | 35 | WHILE (num_pernicious LT max_num) DO BEGIN 36 | num_ones = count_ones(i.ToBinary()) 37 | IF (is_prime_number(num_ones) EQ 1) THEN BEGIN 38 | ;PRINT, i, ' --->', i.ToBinary(), ' ', num_ones, ' ', num_ones.Map(isprime) 39 | num_pernicious = num_pernicious + 1 40 | ENDIF 41 | i = i + 1 42 | ENDWHILE 43 | 44 | 45 | time1 = SYSTIME(/SECONDS) - time0 46 | PRINT, 'Pernicious Numbers (',max_num,'): ', time1, i-1 47 | 48 | RETURN 49 | END 50 | -------------------------------------------------------------------------------- /IDL/timeSeriesRun.pro: -------------------------------------------------------------------------------- 1 | PRINT, 'Job started' 2 | 3 | test_time_series_aoa 4 | 5 | PRINT, 'Job complete' 6 | -------------------------------------------------------------------------------- /Java/.Java2019log-33588669.out.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Java/.Java2019log-33588669.out.swp -------------------------------------------------------------------------------- /Java/testBeliefPropagation.java: -------------------------------------------------------------------------------- 1 | // import java.util.Scanner; 2 | import java.io.*; 3 | import java.util.concurrent.*; 4 | import java.text.DecimalFormat; 5 | import java.text.NumberFormat; 6 | import java.util.Random; 7 | import java.lang.*; 8 | 9 | class testBeliefPropagation { 10 | 11 | public static void main (String[] args) { 12 | 13 | long startTime; 14 | long estimatedTime; 15 | int n; 16 | int dim = 5000; 17 | 18 | // create a scanner so we can read the command-line input 19 | //Scanner scanner = new Scanner(System.in); 20 | 21 | // create instance of Random class 22 | Random rand = new Random(); 23 | 24 | if (args.length > 0) { 25 | try { 26 | n = Integer.parseInt(args[0]); 27 | } catch (NumberFormatException e) { 28 | System.err.println("Argument" + args[0] + " must be an integer."); 29 | System.exit(1); 30 | } 31 | } 32 | 33 | n = Integer.parseInt(args[0]); 34 | 35 | System.out.println("Belief Propagation: "+n); 36 | 37 | double A[][] = new double[dim][dim]; 38 | double x[] = new double[dim]; 39 | double x2[] = new double[dim]; 40 | 41 | double mysum = 0; 42 | double mynorm = 0; 43 | 44 | startTime = System.currentTimeMillis(); 45 | 46 | for (int i=0;i 0) { 23 | try { 24 | n = Integer.parseInt(args[0]); 25 | } catch (NumberFormatException e) { 26 | System.err.println("Argument" + args[0] + " must be an integer."); 27 | System.exit(1); 28 | } 29 | } 30 | 31 | n = Integer.parseInt(args[0]); 32 | double A[][][]=new double[n][n][3]; 33 | 34 | for (int i=0;i listOfWords = new HashMap(); 25 | Scanner in = new Scanner(f); 26 | int i=0; 27 | while(in.hasNext()) 28 | { 29 | String s=in.next(); 30 | //System.out.println(s); 31 | arr.add(s.replaceAll("[^a-zA-Z]", "").toLowerCase()); 32 | // arr.add(s); 33 | } 34 | Iterator itr=arr.iterator(); 35 | while(itr.hasNext()) 36 | { 37 | i++; 38 | 39 | listOfWords.put((String) itr.next(), i); 40 | //System.out.println(listOfWords); //for Printing the words 41 | } 42 | 43 | Set uniqueValues = new HashSet(listOfWords.values()); 44 | 45 | System.out.println("The number of unique words: "+uniqueValues.size()); 46 | estimatedTime = System.nanoTime() - startTime; 47 | System.out.println(" Time: " + formatter.format(estimatedTime / 1000000000d) + " seconds"); 48 | 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Java/testEvaluateFunctions.java: -------------------------------------------------------------------------------- 1 | // import java.util.Scanner; 2 | import java.io.*; 3 | import java.util.concurrent.*; 4 | import java.text.DecimalFormat; 5 | import java.text.NumberFormat; 6 | import java.util.Random; 7 | 8 | class testEvaluateFunctions { 9 | 10 | public static void main (String[] args) { 11 | 12 | long startTime; 13 | long estimatedTime; 14 | int num_iterations = 10000; 15 | double a_min = -1500.0; 16 | double a_max = 1500.0; 17 | double h; 18 | int n; 19 | 20 | // create a scanner so we can read the command-line input 21 | //Scanner scanner = new Scanner(System.in); 22 | 23 | if (args.length > 0) { 24 | try { 25 | n = Integer.parseInt(args[0]); 26 | } catch (NumberFormatException e) { 27 | System.err.println("Argument" + args[0] + " must be an integer."); 28 | System.exit(1); 29 | } 30 | } 31 | 32 | n = Integer.parseInt(args[0]); 33 | 34 | System.out.println("Evaluate Functions: "+n); 35 | 36 | startTime = System.currentTimeMillis(); 37 | 38 | double x[]=new double[n]; 39 | double y[]=new double[n]; 40 | 41 | h = (a_max - a_min)/(n-1); 42 | 43 | for (int i=0;i 0) { 19 | try { 20 | n = Integer.parseInt(args[0]); 21 | } catch (NumberFormatException e) { 22 | System.err.println("Argument" + args[0] + " must be an integer."); 23 | System.exit(1); 24 | } 25 | } 26 | 27 | n = Integer.parseInt(args[0]); 28 | 29 | System.out.println("Fibonacci sequence: "+n); 30 | startTime = System.nanoTime(); 31 | a = itFibN(n); 32 | estimatedTime = System.nanoTime() - startTime; 33 | System.out.println(" Time for iterative Fib: " + formatter.format(estimatedTime / 1000000000d) + " seconds"); 34 | 35 | startTime = System.nanoTime(); 36 | b = recFibN(n); 37 | estimatedTime = System.nanoTime() - startTime; 38 | System.out.println(" Time for recursive Fib: " + formatter.format(estimatedTime / 1000000000d) + " seconds"); 39 | 40 | 41 | } 42 | 43 | // Iterative 44 | public static long itFibN(int n) 45 | { 46 | if (n < 2) 47 | return n; 48 | long ans = 0; 49 | long n1 = 0; 50 | long n2 = 1; 51 | for(n--; n > 0; n--) 52 | { 53 | ans = n1 + n2; 54 | n1 = n2; 55 | n2 = ans; 56 | } 57 | return ans; 58 | } 59 | 60 | // Recursive 61 | public static long recFibN(final int n) 62 | { 63 | return (n < 2) ? n : recFibN(n - 1) + recFibN(n - 2); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /Java/testLookAndSay.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.io.*; 3 | import java.util.concurrent.*; 4 | import java.text.DecimalFormat; 5 | import java.text.NumberFormat; 6 | 7 | class testLookAndSay { 8 | 9 | public static void main (String args[]) { 10 | int n; 11 | long a; 12 | long b; 13 | long startTime; 14 | long estimatedTime; 15 | 16 | NumberFormat formatter = new DecimalFormat("#00000.00000000"); 17 | 18 | if (args.length > 0) { 19 | try { 20 | n = Integer.parseInt(args[0]); 21 | } catch (NumberFormatException e) { 22 | System.err.println("Argument" + args[0] + " must be an integer."); 23 | System.exit(1); 24 | } 25 | } 26 | 27 | n = Integer.parseInt(args[0]); 28 | 29 | System.out.println("Look and say sequence: "+n); 30 | startTime = System.nanoTime(); 31 | 32 | String num = "1223334444"; 33 | for (int i=2;i<=n;i++) { 34 | num = lookandsayseq(num); 35 | } 36 | //System.out.println(num); 37 | 38 | estimatedTime = System.nanoTime() - startTime; 39 | System.out.println(" Time for look and say: " + formatter.format(estimatedTime / 1000000000d) + " seconds"); 40 | 41 | } 42 | 43 | public static String lookandsayseq(String number) 44 | { 45 | StringBuilder result= new StringBuilder(); 46 | 47 | char repeat= number.charAt(0); 48 | number= number.substring(1) + " "; 49 | int times= 1; 50 | 51 | for (char actual: number.toCharArray()) 52 | { 53 | if (actual != repeat) 54 | { 55 | result.append(times + "" + repeat); 56 | times= 1; 57 | repeat= actual; 58 | } 59 | else 60 | { 61 | times+= 1; 62 | } 63 | } 64 | return result.toString(); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /Java/testMarkovChain.java: -------------------------------------------------------------------------------- 1 | // import java.util.Scanner; 2 | import java.io.*; 3 | import java.util.concurrent.*; 4 | import java.text.DecimalFormat; 5 | import java.text.NumberFormat; 6 | import java.util.Random; 7 | import java.lang.*; 8 | 9 | class testMarkovChain { 10 | 11 | public static void main (String[] args) { 12 | 13 | long startTime; 14 | long estimatedTime; 15 | int n; 16 | 17 | // create instance of Random class 18 | Random rand = new Random(); 19 | 20 | if (args.length > 0) { 21 | try { 22 | n = Integer.parseInt(args[0]); 23 | } catch (NumberFormatException e) { 24 | System.err.println("Argument" + args[0] + " must be an integer."); 25 | System.exit(1); 26 | } 27 | } 28 | 29 | n = Integer.parseInt(args[0]); 30 | 31 | System.out.println("Perform Markov Chain calculations: "+n); 32 | 33 | double x[] = new double[2]; 34 | double x2[] = new double[2]; 35 | 36 | double p1 = 0; 37 | double p2 = 0; 38 | 39 | startTime = System.currentTimeMillis(); 40 | 41 | x[0] = 0; 42 | x[1] = 0; 43 | 44 | p1 = Math.exp(Math.sin(5*x[0]) - x[0]*x[0] - x[1]*x[1]); 45 | 46 | for (int k=0;k 0) { 23 | try { 24 | n = Integer.parseInt(args[0]); 25 | } catch (NumberFormatException e) { 26 | System.err.println("Argument" + args[0] + " must be an integer."); 27 | System.exit(1); 28 | } 29 | } 30 | 31 | n = Integer.parseInt(args[0]); 32 | double a[][]=new double[n][n]; 33 | double b[][]=new double[n][n]; 34 | double c[][]=new double[n][n]; 35 | 36 | for (int i=0;i n) { 49 | return false; 50 | } 51 | nn /= 10; 52 | } while (nn > 0); 53 | 54 | return sum == n; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Java/testPerniciousNumbers.java: -------------------------------------------------------------------------------- 1 | // import java.util.Scanner; 2 | import java.io.*; 3 | import java.util.concurrent.*; 4 | import java.text.DecimalFormat; 5 | import java.text.NumberFormat; 6 | 7 | public class testPerniciousNumbers{ 8 | //very simple isPrime since x will be <= Long.SIZE 9 | public static boolean isPrime(int x){ 10 | if(x < 2) return false; 11 | for(int i = 2; i < x; i++){ 12 | if(x % i == 0) return false; 13 | } 14 | return true; 15 | } 16 | 17 | public static int popCount(long x){ 18 | return Long.bitCount(x); 19 | } 20 | 21 | public static void main(String[] args){ 22 | 23 | long startTime; 24 | long estimatedTime; 25 | int max_num; 26 | 27 | if (args.length > 0) { 28 | try { 29 | max_num = Integer.parseInt(args[0]); 30 | } catch (NumberFormatException e) { 31 | System.err.println("Argument" + args[0] + " must be an integer."); 32 | System.exit(1); 33 | } 34 | } 35 | 36 | max_num = Integer.parseInt(args[0]); 37 | 38 | System.out.println("Pernicious number: "+max_num); 39 | 40 | startTime = System.currentTimeMillis(); 41 | 42 | for(long i = 1, n = 0; n < max_num; i++){ 43 | if(isPrime(popCount(i))){ 44 | // System.out.print(i + " "); 45 | n++; 46 | } 47 | } 48 | 49 | estimatedTime = System.currentTimeMillis() - startTime; 50 | NumberFormat formatter = new DecimalFormat("#00000.00000000"); 51 | System.out.println(" Pernicious number: " + formatter.format(estimatedTime / 1000d) + " seconds"); 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Julia/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/.DS_Store -------------------------------------------------------------------------------- /Julia/._.DS_Store: -------------------------------------------------------------------------------- 1 | Mac OS X  2Fx @ATTRxx -------------------------------------------------------------------------------- /Julia/._Julia_2018log-33336899.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._Julia_2018log-33336899.out -------------------------------------------------------------------------------- /Julia/._Julia_2018log-33372690.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._Julia_2018log-33372690.out -------------------------------------------------------------------------------- /Julia/._juliaJobScript.job: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._juliaJobScript.job -------------------------------------------------------------------------------- /Julia/._test_belief_propagation.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_belief_propagation.jl -------------------------------------------------------------------------------- /Julia/._test_compute_FFT.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_compute_FFT.jl -------------------------------------------------------------------------------- /Julia/._test_copy_matrix.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_copy_matrix.jl -------------------------------------------------------------------------------- /Julia/._test_count_unique_words.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_count_unique_words.jl -------------------------------------------------------------------------------- /Julia/._test_evaluate_functions.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_evaluate_functions.jl -------------------------------------------------------------------------------- /Julia/._test_fibonacci.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_fibonacci.jl -------------------------------------------------------------------------------- /Julia/._test_gauss_legendre_quadrature.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_gauss_legendre_quadrature.jl -------------------------------------------------------------------------------- /Julia/._test_laplace_jacobi_4.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_laplace_jacobi_4.jl -------------------------------------------------------------------------------- /Julia/._test_look_and_say.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_look_and_say.jl -------------------------------------------------------------------------------- /Julia/._test_look_and_say_2.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_look_and_say_2.jl -------------------------------------------------------------------------------- /Julia/._test_markov_chain.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_markov_chain.jl -------------------------------------------------------------------------------- /Julia/._test_matrix_multiplication.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_matrix_multiplication.jl -------------------------------------------------------------------------------- /Julia/._test_munchausen.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_munchausen.jl -------------------------------------------------------------------------------- /Julia/._test_sqrt_matrix.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_sqrt_matrix.jl -------------------------------------------------------------------------------- /Julia/._test_time_series_AOA.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_time_series_AOA.jl -------------------------------------------------------------------------------- /Julia/._test_time_series_AOA_multiprocessing.jl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Julia/._test_time_series_AOA_multiprocessing.jl -------------------------------------------------------------------------------- /Julia/.ipynb_checkpoints/Untitled-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 2 6 | } 7 | -------------------------------------------------------------------------------- /Julia/test_belief_propagation.jl: -------------------------------------------------------------------------------- 1 | using BenchmarkTools 2 | using Printf 3 | using Random 4 | using LinearAlgebra 5 | 6 | # Get the number of iterations from the command line. 7 | n, = size(ARGS) 8 | if n < 1 9 | println("Usage: belief.jl N") 10 | println(" ---> Please specify the number of iterations.") 11 | exit() 12 | end 13 | 14 | N = parse(Int, ARGS[1]) 15 | 16 | """ 17 | beliefpropagation(N) 18 | 19 | Runs the belief propagation algorithm N times. 20 | """ 21 | function beliefpropagation(N) 22 | dim = 5000 23 | x = ones(dim) 24 | A = (randn(dim,dim) .+ 1.0)/2.0 25 | 26 | for i = 1:N 27 | x = log.(A*exp.(x)); 28 | x .-= log.(sum(exp.(x))); 29 | end 30 | x 31 | end 32 | 33 | println("--------------------------") 34 | println(@sprintf "Belief calculations: %d" N) 35 | println("--------------------------") 36 | 37 | @btime beliefpropagation(N) 38 | -------------------------------------------------------------------------------- /Julia/test_compute_FFT.jl: -------------------------------------------------------------------------------- 1 | using BenchmarkTools 2 | using Printf 3 | using FFTW 4 | 5 | 6 | # Get the number of data points N from the command line. 7 | N = parse(Int, ARGS[1]) 8 | 9 | println("-----------------------------------------") 10 | println("Compute FFTs: ", N) 11 | println("-----------------------------------------") 12 | println(" ") 13 | 14 | #Take the FFT of the N random data points. 15 | @btime begin 16 | mat = complex.(rand(N, N), randn(N, N)) 17 | result = fft(mat) 18 | result = abs.(result) 19 | end 20 | -------------------------------------------------------------------------------- /Julia/test_copy_matrix.jl: -------------------------------------------------------------------------------- 1 | 2 | using BenchmarkTools 3 | using Printf 4 | 5 | 6 | # Get the dimension from the command line. 7 | n, = size(ARGS) 8 | if n < 1 9 | println("Usage: copyMatrix.jl dim") 10 | println(" ---> Please specify the dimension.") 11 | exit() 12 | end 13 | 14 | dimension = parse(Int, ARGS[1]) 15 | 16 | """ 17 | maxtrixcopy(A) 18 | 19 | Perform the copy operations on matrix A with the given dimensions. 20 | """ 21 | function matrixcopy(A) 22 | N = size(A, 1) 23 | for j = 1:N, i = 1:N 24 | A[i, j, 1] = A[i, j, 2] 25 | A[i, j, 3] = A[i, j, 1] 26 | A[i, j, 2] = A[i, j, 3] 27 | end 28 | end 29 | 30 | 31 | println("-------------------------------") 32 | println(@sprintf "Copy of matrix (loop) %d" dimension) 33 | println("-------------------------------") 34 | 35 | A = randn(dimension, dimension, 3) 36 | 37 | @btime matrixcopy(A) 38 | 39 | println(" ") 40 | 41 | println("--------------------------") 42 | println(@sprintf "Vectorized Copy of matrix %d" dimension) 43 | println("--------------------------") 44 | 45 | A = randn(dimension, dimension, 3) 46 | 47 | @btime begin 48 | A[:, :, 1] = A[:, :, 2] 49 | A[:, :, 3] = A[:, :, 1] 50 | A[:, :, 2] = A[:, :, 3] 51 | end 52 | 53 | println(" ") 54 | -------------------------------------------------------------------------------- /Julia/test_count_unique_words.jl: -------------------------------------------------------------------------------- 1 | using Printf 2 | using BenchmarkTools 3 | using LegacyStrings 4 | 5 | fullstrip(str::AbstractString, chars::AbstractString) = replace(str, Regex("[$chars]") => "") 6 | 7 | punctuation_characters = r"~\`!@#$%^&*()_-+=[{]}\\|;:',<.>/?1234567890" 8 | #punctuation_characters = String("~\`!@#$%^&*()_-+=[{]}\\|;:',<.>/?1234567890") 9 | #punctuation_characters = ASCIIString("~\`!@#$%^&*()_-+=[{]}\\|;:',<.>/?1234567890") 10 | #punctuation_characters = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' 11 | 12 | """ 13 | countwords(filename::String) 14 | 15 | Opens the given file and makes a collection of its unique words. 16 | """ 17 | function countwords(filename::String) 18 | openedfile = open(filename) 19 | wordlist = String[] 20 | for line in eachline(openedfile) 21 | println(line) 22 | words = split( fullstrip(line, punctuation_characters)) 23 | map(word -> push!(wordlist, lowercase(word)), words) 24 | end 25 | close(openedfile) 26 | filter!(!isempty, wordlist) 27 | println("Number of unique words: ", length(wordlist)) 28 | end 29 | 30 | 31 | # Get the text file name from the command line. 32 | n, = size(ARGS) 33 | if n < 1 34 | println("Usage: ") 35 | println(" julia " + ARG[0] + " filename") 36 | println(" ---> Please specify the filename.") 37 | exit() 38 | end 39 | 40 | filename = ARGS[1] 41 | @btime count_word(filename) 42 | 43 | println(" ") 44 | -------------------------------------------------------------------------------- /Julia/test_evaluate_functions.jl: -------------------------------------------------------------------------------- 1 | using BenchmarkTools 2 | using Printf 3 | 4 | 5 | """ 6 | evaluatefunctions(N) 7 | 8 | Evaluates trigonometric functions on N values spaced 9 | evenly between -1500.0 and 1500.0. 10 | """ 11 | function evaluatefunctions(N) 12 | #x = linspace(-1500.0, 1500.0, N) 13 | x = range(-1500.0, stop=1500.0, length=N) 14 | M = 10000 15 | for i in 1:M 16 | y = sin.(x) 17 | x = asin.(y) 18 | y = cos.(x) 19 | x = acos.(y) 20 | y = tan.(x) 21 | x = atan.(y) 22 | end 23 | end 24 | 25 | 26 | # Get the number of values from the command line. 27 | N = parse(Int, ARGS[1]) 28 | 29 | println("-----------------------------------------") 30 | println("Evaluate functions: ", N) 31 | println("-----------------------------------------") 32 | println(" ") 33 | 34 | @btime evaluatefunctions(N) 35 | -------------------------------------------------------------------------------- /Julia/test_fibonacci.jl: -------------------------------------------------------------------------------- 1 | using Printf 2 | using BenchmarkTools 3 | 4 | 5 | # Get the number of iterations from the command line. 6 | n, = size(ARGS) 7 | if n < 1 8 | println("Usage: fibonnaci.jl N") 9 | println(" ---> Please specify the number of iterations.") 10 | exit() 11 | end 12 | 13 | N = parse(Int, ARGS[1]) 14 | 15 | """ 16 | recursive_fibonacci(n) 17 | 18 | Finds the nth Fibonacci number using recursion. 19 | """ 20 | function recursive_fibonacci(n) 21 | if n <= 2 22 | 1.0 23 | else 24 | recursive_fibonacci(n-1) + recursive_fibonacci(n-2); 25 | end 26 | end 27 | 28 | 29 | """ 30 | iterative_fibonacci(n) 31 | 32 | Finds the nth Fibonacci number using iteration. 33 | """ 34 | function iterative_fibonacci(n) 35 | x, y = (0, 1) 36 | for i = 1:n x, y = (y, x + y) end 37 | x 38 | end 39 | 40 | 41 | println("--------------------------") 42 | println(@sprintf "Iterative - Fibonnaci %d" N) 43 | println("--------------------------") 44 | 45 | @btime iterative_fibonacci(N) 46 | 47 | println("--------------------------") 48 | println(@sprintf "Recursive - Fibonnaci %d" N) 49 | println("--------------------------") 50 | 51 | @btime recursive_fibonacci(N) 52 | -------------------------------------------------------------------------------- /Julia/test_gauss_legendre_quadrature.jl: -------------------------------------------------------------------------------- 1 | using BenchmarkTools 2 | using Printf 3 | using LinearAlgebra 4 | 5 | # Get the number of iterations from the command line 6 | n, = size(ARGS) 7 | if n < 1 8 | println("Usage: TestGaussLegendreQuadrature.jl N") 9 | println(" ---> Please specify the number of grid points.") 10 | exit() 11 | end 12 | 13 | N = parse(Int, ARGS[1]) 14 | 15 | """ 16 | gauss(a, b, N) 17 | 18 | Finds the approximate integral over the region [a, b] 19 | with N iterations. 20 | """ 21 | function gauss(a, b, N) 22 | F = eigen(SymTridiagonal(zeros(N), [n/sqrt(4n^2 - 1) for n = 1:N-1])) 23 | return [(F.values[i]+1)*(b-a)/2 + a for i = 1:N], [2*F.vectors[1, i]^2 for i = 1:N]*(b-a)/2 24 | #lambda, Q = eig(SymTridiagonal(zeros(N), [n/sqrt(4n^2 - 1) for n = 1:N-1])) 25 | #return (lambda+1)*(b-a)/2 + a, [2*Q[1, i]^2 for i = 1:N]*(b-a)/2 26 | end 27 | 28 | 29 | println("--------------------------") 30 | println(@sprintf "Gauss-Legendre Quadrature %d" N) 31 | println("--------------------------") 32 | 33 | @btime begin 34 | x, w = gauss(-3, 3, $N) 35 | quad = sum(exp.(x) .* w) 36 | end 37 | 38 | #exact = exp(3) - exp(-3) 39 | #println(quad) 40 | #println(exact) 41 | -------------------------------------------------------------------------------- /Julia/test_look_and_say.jl: -------------------------------------------------------------------------------- 1 | using Printf 2 | using BenchmarkTools 3 | 4 | 5 | """ 6 | lookandsay(n::String) 7 | 8 | Perform the look and say algorithm once on the given string. 9 | """ 10 | function lookandsay(n::String) 11 | sequence = IOBuffer() 12 | i, c = 1, 1 13 | while i ≤ length(n) 14 | if i != length(n) && n[i] == n[i+1] 15 | c += 1 16 | else 17 | print(sequence, c, n[i]) 18 | c = 1 19 | end 20 | i += 1 21 | end 22 | return newstring(take!(sequence)) 23 | end 24 | 25 | 26 | """ 27 | lookandsayseq(n::Integer, startsequence::String) 28 | 29 | Iteratively construct the nth look and say sequence. 30 | """ 31 | function lookandsayseq(n::Integer, startsequence::String) 32 | sequence = Array{String}(n) 33 | sequence[1] = startsequence 34 | if n > 1 35 | for i in 2:n 36 | sequence[i] = lookandsay(sequence[i-1]) 37 | end 38 | end 39 | return sequence 40 | end 41 | 42 | 43 | N = parse(Int, ARGS[1]) 44 | 45 | 46 | println("--------------------------") 47 | println(@sprintf "Look and say sequence: %d" N) 48 | println("--------------------------") 49 | 50 | @btime begin 51 | r = lookandsayseq(N, "1223334444") 52 | end 53 | #println(r[N]) 54 | -------------------------------------------------------------------------------- /Julia/test_look_and_say_2.jl: -------------------------------------------------------------------------------- 1 | using BenchmarkTools 2 | using Printf 3 | 4 | 5 | """ 6 | look_and_say_sequence(startsequence, n) 7 | 8 | Construct the look and say sequence of order n and starting sequence startsequence. 9 | """ 10 | #function look_and_say_sequence(startsequence::String, n::Integer) 11 | function look_and_say_sequence(startsequence, n) 12 | currentsequence = startsequence 13 | 14 | i = 2 15 | 16 | while i <= n 17 | count = 1 18 | tempseries = "" 19 | for j in 2:length(currentsequence) 20 | if currentsequence[j] == currentsequence[j-1] 21 | count += 1 22 | else 23 | tempseries = string(tempseries, count, currentsequence[j-1]) 24 | count = 1 25 | end 26 | end 27 | tempseries = string(tempseries, count, currentsequence[length(currentsequence)]) 28 | currentsequence = tempseries 29 | i += 1 30 | end 31 | return currentsequence 32 | end 33 | 34 | 35 | N = parse(Int, ARGS[1]) 36 | 37 | println("--------------------------") 38 | println(@sprintf "Look and say sequence: %d" N) 39 | println("--------------------------") 40 | 41 | @btime begin 42 | r = look_and_say_sequence("1223334444", N) 43 | end 44 | # println(r) 45 | -------------------------------------------------------------------------------- /Julia/test_markov_chain.jl: -------------------------------------------------------------------------------- 1 | using BenchmarkTools 2 | using Printf 3 | 4 | # Get the number of iterations from the command line 5 | n, = size(ARGS) 6 | if (n < 1) 7 | println("Usage: test_markov_chain.jl N") 8 | println(" ---> Please specify the number of iterations.") 9 | exit() 10 | end 11 | 12 | N = parse(Int, ARGS[1]) 13 | 14 | 15 | """ 16 | function markov_optimized(x,N) 17 | 18 | Operate the Markov chain on two identical inputs x a total of N times. 19 | """ 20 | function markov_optimized(x, N) 21 | x1, x2 = x 22 | f(x1, x2) = exp(sin(x1*5) - x1^2 - x2^2) 23 | p = f(x1, x2) 24 | for n = 1:N 25 | y1 = x1 + 0.01*randn(x1) 26 | y2 = x2 + 0.01*randn(x2) 27 | q = f(y1, y2) 28 | if p*rand() < q 29 | x1 = y1 30 | x2 = y2 31 | p = q 32 | end 33 | end 34 | end 35 | 36 | 37 | """ 38 | function markov(x, y, N) 39 | 40 | Operate the Markov chain on two inputs x, y a total of N times. 41 | """ 42 | function markov(x, y, N) 43 | f(x, y) = exp(sin(x*5) - x^2 - y^2) 44 | p = f(x, y) 45 | for n = 1:N 46 | x2 = x + 0.01*randn() 47 | y2 = y + 0.01*randn() 48 | p2 = f(x2, y2) 49 | if rand() < p2/p 50 | x = x2 51 | y = y2 52 | p = p2 53 | end 54 | end 55 | x, y 56 | end 57 | 58 | # trigger JIT 59 | markov(0.0, 0.0, 10) 60 | 61 | println("--------------------------") 62 | println(@sprintf "Markov Chain calculations: %d" N) 63 | println("--------------------------") 64 | 65 | @btime markov(0.0, 0.0, N) 66 | 67 | #println("--------------------------") 68 | #println(@sprintf "Markov Chain calculations - Opt: %d" N) 69 | #println("--------------------------") 70 | # 71 | @btime markov_optimized([0.0 0.0],N) 72 | -------------------------------------------------------------------------------- /Julia/test_matrix_multiplication.jl: -------------------------------------------------------------------------------- 1 | using Printf 2 | using BenchmarkTools 3 | 4 | 5 | # Get the matrix dimensions from the command line argument. 6 | n, = size(ARGS) 7 | if (n < 1) 8 | println("Usage: matrixMult.jl N") 9 | println(" ---> Please specify the dimensions.") 10 | exit() 11 | end 12 | 13 | N = parse(Int, ARGS[1]) 14 | 15 | 16 | println("----------------------------") 17 | println(@sprintf "Matrix dimensions: %d" N) 18 | println("----------------------------") 19 | println(" ") 20 | 21 | # Multiply matrices A and B. 22 | A = randn(N, N) 23 | B = randn(N, N) 24 | 25 | @btime C = A*B 26 | -------------------------------------------------------------------------------- /Julia/test_munchausen.jl: -------------------------------------------------------------------------------- 1 | using Printf 2 | using BenchmarkTools 3 | 4 | 5 | println("-------------------------------") 6 | println(@sprintf "Compute the first four Munchausen numbers") 7 | println("-------------------------------") 8 | 9 | """ 10 | raisedto(x) 11 | 12 | 13 | Raise x to the power of itself. 14 | """ 15 | function raisedto(x) 16 | if x == 0 17 | return 0 18 | else 19 | return x^x 20 | end 21 | end 22 | 23 | function find_munchausen_numbers() 24 | 25 | power_of_digits = [raisedto(i) for i in 0:9] 26 | 27 | num = 0 28 | i = 0 29 | while num < 4 30 | thisnumber = i 31 | # find the sum of the digits raised to themselves 32 | sumofpowers = 0 33 | while thisnumber > 0 34 | digit = thisnumber % 10 35 | sumofpowers += power_of_digits[digit+1] 36 | thisnumber ÷= 10 37 | end 38 | if i == sumofpowers 39 | num += 1 40 | println("Munchausen number: ", num, " ", i) 41 | end 42 | i += 1 43 | end 44 | end 45 | 46 | 47 | @btime find_munchausen_numbers() 48 | 49 | println(" ") 50 | -------------------------------------------------------------------------------- /Julia/test_pernicious_numbers.jl: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Compute the nth Pernicious number 4 | """ 5 | 6 | using BenchmarkTools 7 | using Printf 8 | using Primes 9 | 10 | # Get the value of of an integer from the command line. 11 | n, = size(ARGS) 12 | if n < 1 13 | println("Usage: test_pernicious_numbers.jl max_num") 14 | println(" ---> Please specify a positive integer.") 15 | exit() 16 | end 17 | 18 | max_num = parse(Int64, ARGS[1]) 19 | 20 | 21 | ispernicious(n::Int64) = isprime(count_ones(n)) 22 | 23 | nextpernicious(n::Int64) = begin n += 1; while !ispernicious(n) n += 1 end; return n end 24 | 25 | function perniciouses(n::Int64) 26 | rst = Vector{Int64}(undef, n) 27 | old_p = 3 28 | for i in 2:n 29 | new_p = nextpernicious(old_p) 30 | old_p = new_p 31 | end 32 | return old_p 33 | end 34 | 35 | perniciouses(a::Integer, b::Integer) = filter(ispernicious, a:b) 36 | 37 | println("Pernicious number of order: ", max_num) 38 | 39 | @btime perniciouses(max_num) 40 | 41 | #println("Pernicious number of order ", max_num, ": ", perniciouses(max_num)) 42 | -------------------------------------------------------------------------------- /Julia/test_read_reverse_file.jl: -------------------------------------------------------------------------------- 1 | 2 | using BenchmarkTools 3 | 4 | 5 | """ 6 | read_reverse_file(filename::String) 7 | 8 | Read an entire file and write its content in 9 | a new file in reverse order. 10 | """ 11 | function read_reverse_file(filename::String) 12 | open(filename) do file_id 13 | lines = readlines(file_id) 14 | end 15 | 16 | rev_filename = "rev_"+basename(filename) 17 | open(rev_filename, "w") do rev_file_id 18 | println(rev_file_id, [reverse(line) for line in reverse(lines)]) 19 | end 20 | end 21 | 22 | 23 | # Get the text file name from the command line. 24 | n, = size(ARGS) 25 | if n < 1 26 | println("Usage: ") 27 | println(" julia " + ARG[0] + " filename") 28 | println(" ---> Please specify the filename.") 29 | exit() 30 | end 31 | 32 | filename = ARGS[1] 33 | @btime read_reverse_file(filename) 34 | 35 | println(" ") 36 | -------------------------------------------------------------------------------- /Julia/test_sqrt_matrix.jl: -------------------------------------------------------------------------------- 1 | using BenchmarkTools 2 | using Printf 3 | 4 | # Get the matrix dimensions N from the command line argument. 5 | N = parse(Int, ARGS[1]) 6 | 7 | A = ones(N, N) 8 | for i = 1:N 9 | A[i, i] = 6 10 | end 11 | 12 | println("--------------------------") 13 | println(@sprintf "Matrix square root: %d" N) 14 | println("--------------------------") 15 | 16 | # Take the square root of matrix A. 17 | @btime begin 18 | B = sqrt(A) 19 | end 20 | -------------------------------------------------------------------------------- /Matlab/test_belief_propagation.m: -------------------------------------------------------------------------------- 1 | 2 | function test_belief_propagation(N) 3 | 4 | fprintf('--------------------------\n') 5 | fprintf('Belief Calculations: %5g \n', N) 6 | fprintf('--------------------------\n') 7 | 8 | tic 9 | 10 | dim = 5000; 11 | A = rand(dim, dim); 12 | x = ones(dim, 1); 13 | 14 | for i=1:N 15 | x = log(A*exp(x)); 16 | x = x - log(sum(exp(x))); 17 | end 18 | 19 | toc 20 | 21 | exit; 22 | -------------------------------------------------------------------------------- /Matlab/test_compute_FFT.m: -------------------------------------------------------------------------------- 1 | 2 | % Determine the FTT of a complex matrix 3 | 4 | function test_compute_FFT(n) 5 | fprintf('--------------------------\n') 6 | fprintf('FFT of complex matrix: %5g \n', n) 7 | fprintf('--------------------------\n') 8 | 9 | tic 10 | 11 | complex_mat = rand(n, n) + 1j * randn(n, n); 12 | result = fft2(complex_mat); 13 | result = abs(result); 14 | 15 | toc 16 | 17 | exit; 18 | -------------------------------------------------------------------------------- /Matlab/test_copy_matrix.m: -------------------------------------------------------------------------------- 1 | % ********************************************************** 2 | % Given a nxnx3 matrix A, we want to perform the operations: 3 | % 4 | % A[i][j][0] = A[i][j][1] 5 | % A[i][j][2] = A[i][j][0] 6 | % A[i][j][1] = A[i][j][2] 7 | % ********************************************************** 8 | 9 | function test_copy_matrix(nx) 10 | %nx = 5000; 11 | 12 | 13 | disp(nx); 14 | 15 | fprintf('--------------------------\n') 16 | fprintf('ji Loop Copy: %5g \n', nx) 17 | fprintf('--------------------------\n') 18 | 19 | A = rand (nx, nx, 3); 20 | tic 21 | 22 | for j = 1:nx 23 | for i = 1:nx 24 | A(i, j, 1) = A(i, j, 2); 25 | A(i, j, 3) = A(i, j, 1); 26 | A(i, j, 2) = A(i, j, 3); 27 | end 28 | end 29 | 30 | toc 31 | 32 | 33 | fprintf('--------------------------\n') 34 | fprintf('Vectorization Copy: %5g \n', nx) 35 | fprintf('--------------------------\n') 36 | 37 | A = rand (nx, nx, 3); 38 | tic 39 | 40 | A(:, :, 1) = A(:, :, 2); 41 | A(:, :, 3) = A(:, :, 1); 42 | A(:, :, 2) = A(:, :, 3); 43 | 44 | toc 45 | 46 | exit; 47 | -------------------------------------------------------------------------------- /Matlab/test_count_unique_words.m: -------------------------------------------------------------------------------- 1 | 2 | function test_count_unique_words(file_name) 3 | 4 | fprintf('--------------------------------------\n') 5 | fprintf('Counting the number of unique words in: %s \n', file_name) 6 | fprintf('--------------------------------------\n') 7 | 8 | tic 9 | 10 | % Import the words from the text file into a cell array 11 | 12 | file = fopen(file_name); 13 | words = textscan(file, '%s'); 14 | status = fclose(file); 15 | 16 | % Get rid of all the characters that are not letters 17 | for i=1:numel(words{1,1}) 18 | ind = find(isstrprop(words{1,1}{i,1}, 'alpha') == 0); 19 | words{1,1}{i,1}(ind)=[]; 20 | words{1,1}{i,1} = lower(words{1,1}{i,1}); 21 | %S = lower(words{1,1}{i,1}); 22 | %words{1,1}{i,1} = S(isstrprop(S,'alpha')); 23 | end 24 | 25 | % Remove entries in words that have zero characters 26 | for i = 1:numel(words{1,1}) 27 | if size(words{1,1}{i,1}, 2) == 0 28 | words{1,1}{i,1} = ' '; 29 | end 30 | end 31 | 32 | % Now count the number of times each word appears 33 | unique_words = unique(words{1,1}); % remove duplication 34 | 35 | fprintf('Number of unique words is: %d \n', numel(unique_words)) 36 | 37 | toc 38 | 39 | exit; 40 | -------------------------------------------------------------------------------- /Matlab/test_evaluate_functions.m: -------------------------------------------------------------------------------- 1 | function test_evaluate_functions(nx) 2 | 3 | fprintf('--------------------------\n') 4 | fprintf('Compute values: %5g \n', nx) 5 | fprintf('--------------------------\n') 6 | 7 | tic 8 | 9 | x = linspace(-1500.0, 1500.0, nx); 10 | M = 10000; 11 | 12 | for i = 1:M 13 | y = sin(x); 14 | x = asin(y); 15 | y = cos(x); 16 | x = acos(y); 17 | y = tan(x); 18 | x = atan(y); 19 | end 20 | 21 | toc 22 | 23 | exit; 24 | -------------------------------------------------------------------------------- /Matlab/test_fibonacci.m: -------------------------------------------------------------------------------- 1 | 2 | function test_fibonacci(n) 3 | 4 | fprintf('--------------------------\n') 5 | fprintf('Iterative Fibonacci: %5g \n', n) 6 | fprintf('--------------------------\n') 7 | 8 | tic 9 | f=test_fibonacci_iter(n); 10 | toc 11 | 12 | fprintf('--------------------------\n') 13 | fprintf('Recursive Fibonacci: %5g \n', n) 14 | fprintf('--------------------------\n') 15 | 16 | tic 17 | f=test_fibonacci_recur(n); 18 | toc 19 | exit; 20 | -------------------------------------------------------------------------------- /Matlab/test_fibonacci_iter.m: -------------------------------------------------------------------------------- 1 | 2 | % Matlab: Iterative fibonacci 3 | 4 | function F=test_fibonacci_iter(n) 5 | 6 | Fn = [1 0]; %Fn(1) is F_{n-2}, Fn(2) is F_{n-1} 7 | F = 0; %F is F_{n} 8 | 9 | for i = (1:abs(n)) 10 | Fn(2) = F; 11 | F = sum(Fn); 12 | Fn(1) = Fn(2); 13 | end 14 | 15 | if n < 0 16 | F = F*((-1)^(n+1)); 17 | end 18 | 19 | end 20 | -------------------------------------------------------------------------------- /Matlab/test_fibonacci_recur.m: -------------------------------------------------------------------------------- 1 | 2 | % Matlab: Recursive fibonacci 3 | function f=test_fibonacci_recur(n) 4 | if n <= 2 5 | f = 1.0; 6 | else 7 | f = test_fibonacci_recur(n-1) + test_fibonacci_recur(n-2); 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /Matlab/test_gauss_legendre_quadrature.m: -------------------------------------------------------------------------------- 1 | 2 | % Adapted from code written by Greg von Winckel - 02/25/2004 3 | % https://www.mathworks.com/matlabcentral/fileexchange/4540-legendre-gauss-quadrature-weights-and-nodes 4 | 5 | function gaussLegendreQuad(M) 6 | 7 | fprintf('--------------------------\n') 8 | fprintf('Gauss-Legendre Quadrature: %5g \n', M) 9 | fprintf('--------------------------\n') 10 | 11 | a = -3.0; 12 | b = 3.0; 13 | 14 | tic 15 | N = M-1; 16 | Np1 = N+1; 17 | Np2 = N+2 18 | 19 | xu=linspace(-1,1,Np1)'; 20 | 21 | % Initial guess 22 | y=cos((2*(0:N)'+1)*pi/(2*N+2))+(0.27/Np1)*sin(pi*xu*N/Np2); 23 | 24 | % Legendre-Gauss Vandermonde Matrix 25 | L=zeros(Np1,Np2); 26 | 27 | % Derivative of LGVM 28 | Lp=zeros(Np1,Np2); 29 | 30 | % Compute the zeros of the N+1 Legendre Polynomial 31 | % using the recursion relation and the Newton-Raphson method 32 | 33 | y0=2; 34 | 35 | % Iterate until new points are uniformly within epsilon of old points 36 | while max(abs(y-y0))>eps 37 | L(:,1)=1; 38 | Lp(:,1)=0; 39 | 40 | L(:,2)=y; 41 | Lp(:,2)=1; 42 | 43 | for k=2:Np1 44 | L(:,k+1)=( (2*k-1)*y.*L(:,k)-(k-1)*L(:,k-1) )/k; 45 | end 46 | 47 | Lp=(Np2)*( L(:,Np1)-y.*L(:,Np2) )./(1-y.^2); 48 | 49 | y0=y; 50 | y=y0-L(:,Np2)./Lp; 51 | end 52 | 53 | % Linear map from[-1,1] to [a,b] 54 | x=(a*(1-y)+b*(1+y))/2; 55 | 56 | % Compute the weights 57 | w=(b-a)./((1-y.^2).*Lp.^2)*(Np2/Np1)^2; 58 | 59 | integral_value = w'*exp(x); 60 | 61 | toc 62 | 63 | exit; 64 | -------------------------------------------------------------------------------- /Matlab/test_laplace_jacobi_4_loops.m: -------------------------------------------------------------------------------- 1 | %############################################### 2 | % Numerical solution of the Laplace's equation. 3 | % 4 | % u + u = 0 5 | % xx yy 6 | % 7 | % Fourth-order compact Scheme 8 | % Jacobi's iteration 9 | %############################################### 10 | 11 | function test_laplace_jacobi_4_loops(nx) 12 | x_min = 0; 13 | x_max = 1; 14 | y_min = 0; 15 | y_max = 1; 16 | 17 | ny = nx; 18 | 19 | dx = (x_max - x_min)/(nx - 1); 20 | dy = (y_max - y_min)/(ny - 1); 21 | 22 | x = x_min:dx:x_max; 23 | y = y_min:dy:y_max; 24 | 25 | n_iter = 10000; 26 | eps = 1e-6; 27 | 28 | u = zeros(nx,ny); 29 | u(:, 1) = sin(x.*pi); 30 | u(:, end) = sin(x.*pi)*exp(-pi); 31 | err = Inf; 32 | count = 0; 33 | 34 | tic 35 | 36 | while err > eps && count < n_iter 37 | count = count + 1; 38 | u_old = u; 39 | for j = 2:ny-1 40 | for i=2:nx-1 41 | u(i, j) = ((u(i-1, j) + u(i+1, j) + u(i, j-1) + u(i, j+1))*4.0 + u(i-1, j-1) + u(i-1, j+1) + u(i+1, j-1) + u(i+1, j+1))/20.0; 42 | end 43 | end 44 | v = (u - u_old); 45 | err = sqrt(v(:).'*v(:)); 46 | end 47 | 48 | fprintf('Jacobi with Matlab - for loops \n'); 49 | fprintf(' Number of iterations: %5g \n', count); 50 | fprintf(' Error: %12.10f \n', err); 51 | 52 | toc 53 | 54 | exit; 55 | -------------------------------------------------------------------------------- /Matlab/test_laplace_jacobi_4_vect.m: -------------------------------------------------------------------------------- 1 | %############################################### 2 | % Numerical solution of the Laplace's equation. 3 | % 4 | % u + u = 0 5 | % xx yy 6 | % 7 | % Fourth-order compact Scheme 8 | % Jacobi's iteration 9 | %############################################### 10 | 11 | function test_laplace_jacobi_4_vect(nx) 12 | x_min = 0; 13 | x_max = 1; 14 | y_min = 0; 15 | y_max = 1; 16 | 17 | %nx = 100; 18 | ny = nx; 19 | 20 | dx = (x_max - x_min) / (nx - 1); 21 | dy = (y_max - y_min) / (ny - 1); 22 | 23 | x = x_min:dx:x_max; 24 | y = y_min:dy:y_max; 25 | 26 | n_iter = 10000; 27 | eps = 1e-6; 28 | 29 | u = zeros(nx,ny); 30 | u(:,1) = sin(x.*pi); 31 | u(:,end) = sin(x.*pi)*exp(-pi); 32 | err = Inf; 33 | count = 0; 34 | 35 | tic 36 | 37 | while err > eps && count < n_iter 38 | count = count + 1; 39 | u_old = u; 40 | u(2:end-1, 2:end-1) = ((u(1:end-2, 2:end-1) + u(3:end, 2:end-1) + u(2:end-1, 1:end-2) + u(2:end-1, 3:end))*4.0 + u(1:end-2, 1:end-2) + u(1:end-2, 3:end) + u(3:end, 1:end-2) + u(3:end, 3:end))/20.0; 41 | v = (u - u_old); 42 | err = sqrt(v(:).'*v(:)); 43 | end 44 | 45 | fprintf('Jacobi with Matlab - Vectorization \n'); 46 | fprintf(' Number of iterations: %5g \n', count); 47 | fprintf(' Error: %12.10f \n', err); 48 | 49 | toc 50 | exit; 51 | -------------------------------------------------------------------------------- /Matlab/test_look_and_say.m: -------------------------------------------------------------------------------- 1 | 2 | %---------------------------------------------------------- 3 | % Construct the look and say sequence of order num and 4 | % starting sequence, startSeq (string). 5 | %---------------------------------------------------------- 6 | 7 | function test_look_and_say(num) 8 | fprintf('--------------------------\n') 9 | fprintf('Look and say sequence: %5g \n', num) 10 | fprintf('--------------------------\n') 11 | 12 | tic 13 | 14 | start_sequence = '1223334444'; 15 | i = 1; 16 | 17 | while (i <= num) 18 | if (i == 1) 19 | current_sequence = start_sequence; 20 | else 21 | count = 1; 22 | temp_series = ''; 23 | for j=2:length(current_sequence) 24 | if (current_sequence(j) == current_sequence(j-1)) 25 | count = count + 1; 26 | else 27 | temp_series = strcat(temp_series, num2str(count), current_sequence(j-1)); 28 | count = 1; 29 | end 30 | end 31 | temp_series = strcat(temp_series, num2str(count), current_sequence(length(current_sequence))); 32 | current_sequence = temp_series; 33 | end 34 | i = i + 1; 35 | end 36 | %fprintf(' %s \n', current_sequence); 37 | 38 | toc 39 | exit; -------------------------------------------------------------------------------- /Matlab/test_markov_chain.m: -------------------------------------------------------------------------------- 1 | 2 | function test_markov_chain(N) 3 | tic 4 | f = @(x) exp(sin(x(1)*5) - x(1)^2 - x(2)^2); 5 | x = zeros(2); 6 | p = f(x); 7 | for n=1:N 8 | x2 = x + .01*randn(size(x)); 9 | p2 = f(x2); 10 | if rand < p2/p 11 | x = x2; 12 | p = p2; 13 | end 14 | end 15 | toc 16 | end 17 | -------------------------------------------------------------------------------- /Matlab/test_matrix_multiplication.m: -------------------------------------------------------------------------------- 1 | % ********************************************************** 2 | % Given two nxn matrices A and B, we perform: 3 | % C = A x B 4 | % ********************************************************** 5 | 6 | function test_matrix_multiplication(nx) 7 | A = rand (nx); 8 | B = rand (nx); 9 | 10 | disp(nx); 11 | 12 | tic 13 | 14 | AB = A * B; 15 | 16 | toc 17 | 18 | exit; 19 | 20 | -------------------------------------------------------------------------------- /Matlab/test_munchausen_number.m: -------------------------------------------------------------------------------- 1 | 2 | function test_munchausen_number() 3 | 4 | fprintf('--------------------------\n') 5 | fprintf('Determine the first four Munchausen numbers \n') 6 | fprintf('--------------------------\n') 7 | 8 | tic 9 | 10 | count = 0; 11 | i = 0; 12 | while(count < 4) 13 | n = i; 14 | % list(map(int,str(i))) 15 | num = 0; 16 | while(n > 0) 17 | k=mod(n,10); 18 | if (k == 0) 19 | answer=k; 20 | else 21 | answer=k^k; 22 | end 23 | num = num + answer; 24 | n = floor(n/10); 25 | end 26 | 27 | if (num == i) 28 | count = count + 1; 29 | fprintf('Munchausen number %2g: %12g \n', count, i) 30 | end 31 | i = i + 1; 32 | end 33 | 34 | toc 35 | 36 | exit; 37 | -------------------------------------------------------------------------------- /Matlab/test_pernicious_numbers.m: -------------------------------------------------------------------------------- 1 | 2 | % ----------------------------------- 3 | % Determine the Nth pernicious number 4 | % ----------------------------------- 5 | 6 | function test_pernicious_numbers(N) 7 | tic 8 | 9 | i = 1; 10 | num_pernicious = 0; 11 | 12 | while num_pernicious < N 13 | binStr = dec2bin(i); 14 | y = length(find(binStr=='1')); 15 | if (isprime(y) == 1) 16 | %if (is_prime_number(y) == 1) 17 | num_pernicious = num_pernicious + 1; 18 | %fprintf('Pernicious number: %8g %10g %10g \n', N, i, y) 19 | end 20 | i = i + 1; 21 | end 22 | 23 | toc 24 | 25 | fprintf('Pernicious number: %8g %10g \n', N, i-1) 26 | 27 | exit; 28 | 29 | -------------------------------------------------------------------------------- /Matlab/test_sqrt_matrix.m: -------------------------------------------------------------------------------- 1 | %------------------------------------------------------------ 2 | % Given a matrix A, we are looking for the matrix B such that 3 | % 4 | % A = B*B 5 | % 6 | % The matrix A has 6s on the diagonal and 1s else where. 7 | %------------------------------------------------------------ 8 | 9 | function test_sqrt_matrix.m(n) 10 | fprintf('--------------------------\n') 11 | fprintf('Square root of a matrix: %5g \n', n) 12 | fprintf('--------------------------\n') 13 | 14 | A = ones(n, n); 15 | for i = 1:n 16 | A(i, i) = 6; 17 | end 18 | 19 | tic 20 | B = sqrtm(A); 21 | toc 22 | exit; 23 | 24 | -------------------------------------------------------------------------------- /Matlab/test_time_series_AOA.m: -------------------------------------------------------------------------------- 1 | fprintf('--------------------------\n') 2 | fprintf('Reading netCDF files \n') 3 | fprintf('--------------------------\n') 4 | 5 | tic 6 | 7 | var_name = 'aoa'; 8 | start_year = 1990; 9 | end_year = 2009; 10 | 11 | first_file = 0; 12 | 13 | num_days = 0; 14 | coefficient = 365.5; 15 | 16 | reference_latitude = -86.0; 17 | 18 | reference_directory = '../Data/'; 19 | 20 | % Loop over the years 21 | for year = start_year:end_year 22 | %fprintf('Processing files for Year %5g \n', year) 23 | 24 | directory_y = strcat(reference_directory, 'Y', num2str(year), '/'); 25 | list_files = dir(strcat(directory_y, 'runAOA.TR.', num2str(year), '*_1200z.nc4')); 26 | 27 | num_days = num_days + numel(list_files); 28 | 29 | % Loop over the daily files 30 | for index = 1:numel(list_files) 31 | filepath = [directory_y, list_files(index).name]; 32 | 33 | % Extract information if it is the first file 34 | if first_file == 0 35 | longitudes = ncread(filepath, 'lon'); 36 | latitudes = ncread(filepath, 'lat'); 37 | levels = ncread(filepath, 'lev'); 38 | [num_longitudes m] = size(longitudes); 39 | [num_latitudes m] = size(latitudes); 40 | [num_levels m] = size(levels); 41 | 42 | lat_index = find(latitudes == reference_latitude); 43 | 44 | %levels = calcPressureLevels(num_levels); 45 | end; 46 | 47 | % Read the daily average age of air 48 | var = ncread(filepath, var_name, [1 lat_index 1 1], [Inf 1 Inf 1], [1 1 1 1]) /coefficient; 49 | 50 | % Determine the zonal mean 51 | temp_var = mean(var,1); 52 | temp_var = squeeze(temp_var); 53 | 54 | % Stack the daily values into an existing array 55 | if first_file == 0 56 | first_file = 1; 57 | data_val = temp_var; 58 | else 59 | data_val = [data_val, temp_var]; 60 | end 61 | end 62 | end 63 | 64 | % End time 65 | toc 66 | 67 | if num_days == 7305 68 | fprintf('Succesfully processed %5g files \n', num_days) 69 | else 70 | fprintf('Only processed %5g files. Verify that all is well! \n', num_days) 71 | end 72 | -------------------------------------------------------------------------------- /Matlab/timeSeries_AOA.m: -------------------------------------------------------------------------------- 1 | % How to run this script: 2 | % 3 | % time matlab -nodisplay -nodesktop -r "run timeSeries_AOA.m" 4 | % 5 | % Start time 6 | %----------- 7 | fprintf('--------------------------\n') 8 | fprintf('Reading netCDF files \n') 9 | fprintf('--------------------------\n') 10 | 11 | tic 12 | 13 | vName = 'aoa'; 14 | begYear = 1990; 15 | endYear = 2009; 16 | 17 | firstFile = 0; 18 | 19 | numDays = 0; 20 | coef = 365.5; 21 | 22 | ref_lat = -86.0; 23 | 24 | refDIR = '../Data/'; 25 | 26 | % Loop over the years 27 | %-------------------- 28 | for year = begYear:endYear 29 | %fprintf('Processing files for Year %5g \n', year) 30 | 31 | dirY = strcat(refDIR, 'Y', num2str(year), '/'); 32 | listFiles = dir(strcat(dirY, 'runAOA.TR.', num2str(year), '*_1200z.nc4')); 33 | 34 | numDays = numDays + numel(listFiles); 35 | 36 | % Loop over the daily files 37 | %-------------------------- 38 | for idx = 1:numel(listFiles) 39 | filepath = [dirY, listFiles(idx).name]; 40 | 41 | % Extract information if it is the first file 42 | %-------------------------------------------- 43 | if firstFile == 0 44 | lons = ncread(filepath, 'lon'); 45 | lats = ncread(filepath, 'lat'); 46 | levs = ncread(filepath, 'lev'); 47 | [nlons m] = size(lons); 48 | [nlats m] = size(lats); 49 | [nlevs m] = size(levs); 50 | 51 | lat_index = find(lats == ref_lat); 52 | 53 | % levs = calcPressureLevels(nlevs); 54 | end; 55 | 56 | % Read the daily average age of air 57 | %---------------------------------- 58 | var = ncread(filepath, vName, [1 lat_index 1 1], [Inf 1 Inf 1], [1 1 1 1]) /coef; 59 | 60 | % Determine the zonal mean 61 | %------------------------- 62 | tempVar = mean(var,1); 63 | tempVar = squeeze(tempVar); 64 | 65 | % Stack the daily values into an existing array 66 | %---------------------------------------------- 67 | if firstFile == 0 68 | firstFile = 1; 69 | dataVal = tempVar; 70 | else 71 | dataVal = [dataVal,tempVar]; 72 | end 73 | end 74 | end 75 | 76 | % End time 77 | %----------- 78 | toc 79 | 80 | if numDays == 7305 81 | fprintf('Succesfully processed %5g files \n', numDays) 82 | else 83 | fprintf('Only processed %5g files. Verify that all is well! \n', numDays) 84 | end 85 | -------------------------------------------------------------------------------- /Plots/fig_languages_histo_Aug2021.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Plots/fig_languages_histo_Aug2021.png -------------------------------------------------------------------------------- /Plots/fig_languages_histo_May2020.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Plots/fig_languages_histo_May2020.png -------------------------------------------------------------------------------- /Plots/fig_languages_histo_Sep2019.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Plots/fig_languages_histo_Sep2019.png -------------------------------------------------------------------------------- /Plots/fig_languages_scatter_Aug2021.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Plots/fig_languages_scatter_Aug2021.png -------------------------------------------------------------------------------- /Plots/fig_languages_scatter_May2020.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Plots/fig_languages_scatter_May2020.png -------------------------------------------------------------------------------- /Plots/fig_languages_scatter_Sep2019.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Plots/fig_languages_scatter_Sep2019.png -------------------------------------------------------------------------------- /Python/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/.DS_Store -------------------------------------------------------------------------------- /Python/._.DS_Store: -------------------------------------------------------------------------------- 1 | Mac OS X  2Fx @ATTRxx -------------------------------------------------------------------------------- /Python/._Python local results.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._Python local results.txt -------------------------------------------------------------------------------- /Python/._README.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._README.txt -------------------------------------------------------------------------------- /Python/._decoratorTimer.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._decoratorTimer.pyc -------------------------------------------------------------------------------- /Python/._decorator_timer.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._decorator_timer.py -------------------------------------------------------------------------------- /Python/._pythonJobScript_Intel.job: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._pythonJobScript_Intel.job -------------------------------------------------------------------------------- /Python/._pythonJobScript_discover.job: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._pythonJobScript_discover.job -------------------------------------------------------------------------------- /Python/._pythonJobScript_local.job: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._pythonJobScript_local.job -------------------------------------------------------------------------------- /Python/._pythonJobScript_numba.job: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._pythonJobScript_numba.job -------------------------------------------------------------------------------- /Python/._test_belief_propagation.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_belief_propagation.py -------------------------------------------------------------------------------- /Python/._test_compute_FFT.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_compute_FFT.py -------------------------------------------------------------------------------- /Python/._test_copy_matrix.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_copy_matrix.py -------------------------------------------------------------------------------- /Python/._test_copy_matrix_numba.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_copy_matrix_numba.py -------------------------------------------------------------------------------- /Python/._test_count_unique_words.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_count_unique_words.py -------------------------------------------------------------------------------- /Python/._test_digital_root.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_digital_root.py -------------------------------------------------------------------------------- /Python/._test_evaluate_functions.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_evaluate_functions.py -------------------------------------------------------------------------------- /Python/._test_fibonacci.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_fibonacci.py -------------------------------------------------------------------------------- /Python/._test_fibonacci_numba.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_fibonacci_numba.py -------------------------------------------------------------------------------- /Python/._test_gauss_legendre_quadrature.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_gauss_legendre_quadrature.py -------------------------------------------------------------------------------- /Python/._test_laplace_jacobi_4.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_laplace_jacobi_4.py -------------------------------------------------------------------------------- /Python/._test_laplace_jacobi_4_numba.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_laplace_jacobi_4_numba.py -------------------------------------------------------------------------------- /Python/._test_look_and_say.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_look_and_say.py -------------------------------------------------------------------------------- /Python/._test_markov_chain.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_markov_chain.py -------------------------------------------------------------------------------- /Python/._test_matrix_multiplication.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_matrix_multiplication.py -------------------------------------------------------------------------------- /Python/._test_matrix_multiplication_numba.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_matrix_multiplication_numba.py -------------------------------------------------------------------------------- /Python/._test_munchausen_number.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_munchausen_number.py -------------------------------------------------------------------------------- /Python/._test_sqrt_matrix.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_sqrt_matrix.py -------------------------------------------------------------------------------- /Python/._test_time_series_AOA.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_time_series_AOA.py -------------------------------------------------------------------------------- /Python/._test_time_series_AOA_multiproc.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/._test_time_series_AOA_multiproc.py -------------------------------------------------------------------------------- /Python/__pycache__/benchmark_decorator.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/Python/__pycache__/benchmark_decorator.cpython-36.pyc -------------------------------------------------------------------------------- /Python/python_job_script_numba: -------------------------------------------------------------------------------- 1 | #!/bin/csh -f 2 | 3 | #SBATCH --time=00:30:00 4 | #SBATCH --job-name=python_numba 5 | #SBATCH --ntasks=40 6 | #SBATCH --constraint=sky 7 | #SBATCH -A j1008 8 | #SBATCH --mail-type=BEGIN 9 | #SBATCH --mail-type=END 10 | #SBATCH -o Python2021log_Numba-%j.out 11 | 12 | 13 | ####################################################################### 14 | # System Environment Variables 15 | ####################################################################### 16 | 17 | umask 022 18 | 19 | limit 20 | 21 | source /usr/share/modules/init/csh 22 | module purge 23 | 24 | module load python/GEOSpyD/Min4.9.2_py3.9 25 | #module load python/GEOSpyD/Ana2019.10_py3.7 26 | 27 | echo '-------------------------' 28 | echo 'Numba - Copy of matrix' 29 | echo '-------------------------' 30 | python test_copy_matrix_numba.py 5000 31 | python test_copy_matrix_numba.py 7000 32 | python test_copy_matrix_numba.py 9000 33 | 34 | echo '-------------------------' 35 | echo 'Numba - matrix multiplication' 36 | echo '-------------------------' 37 | python test_matrix_multiplication_numba.py 1500 38 | python test_matrix_multiplication_numba.py 1750 39 | python test_matrix_multiplication_numba.py 2000 40 | 41 | echo '-------------------------' 42 | echo 'Numba Belief Propagation' 43 | echo '-------------------------' 44 | python test_belief_propagation_numba.py 250 45 | python test_belief_propagation_numba.py 500 46 | python test_belief_propagation_numba.py 1000 47 | 48 | echo '-------------------------' 49 | echo 'Numba - Fibonacci Sequence' 50 | echo '-------------------------' 51 | python test_fibonacci_numba.py 25 52 | python test_fibonacci_numba.py 35 53 | python test_fibonacci_numba.py 45 54 | 55 | echo '-------------------------' 56 | echo 'Numba - Jacobi iterative solver' 57 | echo '-------------------------' 58 | python test_laplace_jacobi_4_numba.py 100 59 | python test_laplace_jacobi_4_numba.py 150 60 | python test_laplace_jacobi_4_numba.py 200 61 | 62 | echo '-------------------------' 63 | echo ' Numba Evaluation of functions' 64 | echo '-------------------------' 65 | python test_evaluate_functions_numba.py 80000 66 | python test_evaluate_functions_numba.py 90000 67 | python test_evaluate_functions_numba.py 100000 68 | 69 | -------------------------------------------------------------------------------- /Python/test_belief_propagation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | import numpy as np 5 | import sys 6 | import benchmark_decorator as dectimer 7 | 8 | @dectimer.bench_time(3) 9 | def belief_propagation(N): 10 | """ 11 | Run the belief propagation algorithm N times 12 | """ 13 | dim = 5000 14 | A = np.random.rand(dim, dim) 15 | x = np.ones((dim,)) 16 | 17 | for i in range(N): 18 | x = np.log(np.dot(A, np.exp(x))) 19 | x -= np.log(np.sum(np.exp(x))) 20 | return x 21 | 22 | 23 | if len(sys.argv) < 1: 24 | print('Usage:') 25 | print(' python ' + sys.argv[0] + ' N') 26 | print('Please specify the number of iterations.') 27 | sys.exit() 28 | 29 | N = int(sys.argv[1]) 30 | 31 | print('Belief calculations:', N) 32 | 33 | y = belief_propagation(N) 34 | -------------------------------------------------------------------------------- /Python/test_belief_propagation_numba.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | import numpy as np 5 | import sys 6 | from numba import njit 7 | from numba import prange 8 | import benchmark_decorator as dectimer 9 | 10 | @dectimer.bench_time(3) 11 | @njit 12 | def belief_propagation(N): 13 | """ 14 | Run the belief propagation algorithm N times 15 | """ 16 | dim = 5000 17 | A = np.random.rand(dim, dim) 18 | x = np.ones((dim,)) 19 | 20 | for i in prange(N): 21 | x = np.log(np.dot(A, np.exp(x))) 22 | x -= np.log(np.sum(np.exp(x))) 23 | return x 24 | 25 | 26 | if len(sys.argv) < 1: 27 | print('Usage:') 28 | print(' python ' + sys.argv[0] + ' N') 29 | print('Please specify the number of iterations.') 30 | sys.exit() 31 | 32 | N = int(sys.argv[1]) 33 | 34 | print('Numba - Belief calculations:', N) 35 | 36 | y = belief_propagation(N) 37 | -------------------------------------------------------------------------------- /Python/test_compute_FFT.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | import numpy as np 6 | import numpy.random as rn 7 | import sys 8 | import benchmark_decorator as dectimer 9 | 10 | 11 | @dectimer.bench_time(3) 12 | def compute_FFT(n): 13 | """ 14 | Compute the FFT of an n-by-n matrix of data 15 | """ 16 | matrix = rn.rand(n, n) + 1j * rn.randn(n, n) 17 | result = np.fft.fft2(matrix) 18 | result = np.abs(result) 19 | 20 | 21 | n = int(sys.argv[1]) 22 | 23 | print('FFT: ', n) 24 | 25 | compute_FFT(n) 26 | 27 | print(' ') 28 | -------------------------------------------------------------------------------- /Python/test_copy_matrix.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | import numpy as np 6 | import sys 7 | import benchmark_decorator as dectimer 8 | 9 | 10 | @dectimer.bench_time(3) 11 | def serial_copy(A): 12 | """ 13 | Perform copies of elements in matrix A iteratively 14 | """ 15 | N = A.shape[0] 16 | for i in range(N): 17 | for j in range(N): 18 | A[i, j, 0] = A[i, j, 1] 19 | A[i, j, 2] = A[i, j, 0] 20 | A[i, j, 1] = A[i, j, 2] 21 | 22 | 23 | @dectimer.bench_time(3) 24 | def vector_copy(A): 25 | """ 26 | Perform copies of of elements in matrix A 27 | with vectorization 28 | """ 29 | A[:, :, 0] = A[:, :, 1] 30 | A[:, :, 2] = A[:, :, 0] 31 | A[:, :, 1] = A[:, :, 2] 32 | 33 | 34 | if len(sys.argv) < 1: 35 | print('Usage:') 36 | print(' python ' + sys.argv[0] + ' dimension') 37 | print('Please specify matrix dimensions') 38 | sys.exit() 39 | 40 | dimension = int(sys.argv[1]) 41 | 42 | print("Copy of a matrix: ", dimension) 43 | 44 | A = np.random.rand(dimension, dimension, 3) 45 | serial_copy(A) 46 | 47 | A = np.random.randn(dimension, dimension, 3) 48 | vector_copy(A) 49 | 50 | print(' ') 51 | -------------------------------------------------------------------------------- /Python/test_copy_matrix_numba.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | import numpy as np 6 | import sys 7 | from numba import njit 8 | from numba import prange 9 | import benchmark_decorator as dectimer 10 | 11 | 12 | @dectimer.bench_time(3) 13 | @njit 14 | def serial_copy(A): 15 | """ 16 | Perform copies of elements in matrix A iteratively 17 | """ 18 | N = A.shape[0] 19 | for i in prange(N): 20 | for j in prange(N): 21 | A[i, j, 0] = A[i, j, 1] 22 | A[i, j, 2] = A[i, j, 0] 23 | A[i, j, 1] = A[i, j, 2] 24 | 25 | 26 | @dectimer.bench_time(3) 27 | @njit 28 | def vector_copy(A): 29 | """ 30 | Perform copies of of elements in matrix A with vectorization 31 | """ 32 | A[:, :, 0] = A[:, :, 1] 33 | A[:, :, 2] = A[:, :, 0] 34 | A[:, :, 1] = A[:, :, 2] 35 | 36 | 37 | if len(sys.argv) < 1: 38 | print('Usage:') 39 | print(' python ' + sys.argv[0] + ' dimension') 40 | print('Please specify matrix dimensions') 41 | sys.exit() 42 | 43 | dimension = int(sys.argv[1]) 44 | 45 | print("Numba -- Copy of a matrix: ", dimension) 46 | 47 | A = np.random.rand(dimension, dimension, 3) 48 | serial_copy(A) 49 | 50 | A = np.random.randn(dimension, dimension, 3) 51 | vector_copy(A) 52 | 53 | print(' ') 54 | -------------------------------------------------------------------------------- /Python/test_count_unique_words.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | from collections import defaultdict 6 | import sys 7 | import benchmark_decorator as dectimer 8 | 9 | punctuation_characters = "~`!@#$%^&*()_-+=[{]}\|;:',<.>/?1234567890" 10 | 11 | #--------------------- 12 | # Function: strip_word 13 | #--------------------- 14 | def strip_word(word): 15 | """ 16 | Remove special characters from word 17 | """ 18 | return "".join([x for x in word if x not in 19 | punctuation_characters]).strip('\"').lower() 20 | 21 | #--------------------------------- 22 | # Function: count_words_dictionary 23 | #--------------------------------- 24 | @dectimer.bench_time(3) 25 | def count_words_dictionary(file_name): 26 | """ 27 | Find unique words using a dictionary 28 | """ 29 | dictionary = defaultdict(int) 30 | for word in open(file_name).read().split(): 31 | dictionary[strip_word(word)] += 1 32 | del dictionary[''] 33 | return len(dictionary) 34 | 35 | #-------------------------- 36 | # Function: count_words_set 37 | #-------------------------- 38 | @dectimer.bench_time(3) 39 | def count_words_set(file_name): 40 | """ 41 | Find unique words using a set 42 | """ 43 | with open(file_name, "r") as file_id: 44 | lines = file_id.read().splitlines() 45 | 46 | uniques = set() 47 | for line in lines: 48 | uniques |= set(strip_word(m) for m in line.split()) 49 | uniques.remove('') 50 | #print(uniques) 51 | return len(uniques) 52 | 53 | 54 | if len(sys.argv) < 1: 55 | print('Usage:') 56 | print(' python ' + sys.argv[0] + ' file_name') 57 | print('Please specify the file name') 58 | sys.exit() 59 | 60 | file_name = sys.argv[1] 61 | 62 | n = count_words_dictionary(file_name) 63 | print("Dictionary - Number of distinct words in %s is: %d" % (file_name, n)) 64 | print(' ') 65 | 66 | n = count_words_set(file_name) 67 | print("Set - Number of distinct words in %s is: %d" % (file_name, n)) 68 | print(' ') 69 | -------------------------------------------------------------------------------- /Python/test_digital_root.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | import sys 6 | import benchmark_decorator as dectimer 7 | 8 | 9 | @dectimer.bench_time(3) 10 | def compute_digital_root(n): 11 | """ 12 | Compute the digital root of the number n 13 | """ 14 | # If num is 0. 15 | if (n == "0"): 16 | return 0 17 | 18 | # Count sum of digits under mod 9 19 | answer = 0 20 | for i in range(0, len(n)): 21 | answer = (answer + int(n[i])) % 9 22 | 23 | # If digit sum is multiple of 9, answer 24 | # 9, else remainder with 9. 25 | if(answer == 0): 26 | return 9 27 | else: 28 | return answer % 9 29 | 30 | 31 | if len(sys.argv) < 2: 32 | print('Usage:') 33 | print(' python ' + sys.argv[0] + ' N') 34 | print('Please specify a number.') 35 | sys.exit() 36 | 37 | # N = int(sys.argv[1]) 38 | N = sys.argv[1] 39 | 40 | print('Digital root of : ', N) 41 | 42 | compute_digital_root(N) 43 | 44 | print(' ') 45 | -------------------------------------------------------------------------------- /Python/test_evaluate_functions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | import numpy as np 6 | import sys 7 | import benchmark_decorator as dectimer 8 | 9 | #----------------------------- 10 | # Function: evaluate_functions 11 | #----------------------------- 12 | @dectimer.bench_time(3) 13 | def evaluate_functions(n): 14 | """ 15 | Evaluate the trigononmetric functions for n values evenly 16 | spaced over the interval [-1500.00, 1500.00] 17 | """ 18 | vector1 = np.linspace(-1500.00, 1500.0, n) 19 | iterations = 10000 20 | for i in range(iterations): 21 | vector2 = np.sin(vector1) 22 | vector1 = np.arcsin(vector2) 23 | vector2 = np.cos(vector1) 24 | vector1 = np.arccos(vector2) 25 | vector2 = np.tan(vector1) 26 | vector1 = np.arctan(vector2) 27 | 28 | n = int(sys.argv[1]) 29 | 30 | print('Evaluate Function: ', n) 31 | 32 | evaluate_functions(n) 33 | 34 | print(' ') 35 | -------------------------------------------------------------------------------- /Python/test_evaluate_functions_numba.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | import numpy as np 6 | import sys 7 | from numba import njit 8 | from numba import prange 9 | import benchmark_decorator as dectimer 10 | 11 | #----------------------------- 12 | # Function: evaluate_functions 13 | #----------------------------- 14 | @dectimer.bench_time(3) 15 | @njit(parallel=True) 16 | def evaluate_functions(n): 17 | """ 18 | Evaluate the trigononmetric functions for n values evenly 19 | spaced over the interval [-1500.00, 1500.00] 20 | """ 21 | vector1 = np.linspace(-1500.00, 1500.0, n) 22 | iterations = 10000 23 | for i in prange(iterations): 24 | vector2 = np.sin(vector1) 25 | vector1 = np.arcsin(vector2) 26 | vector2 = np.cos(vector1) 27 | vector1 = np.arccos(vector2) 28 | vector2 = np.tan(vector1) 29 | vector1 = np.arctan(vector2) 30 | 31 | n = int(sys.argv[1]) 32 | 33 | print('Numba -- Evaluate Function: ', n) 34 | 35 | evaluate_functions(n) 36 | 37 | print(' ') 38 | -------------------------------------------------------------------------------- /Python/test_fibonacci.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | import sys 6 | import benchmark_decorator as dectimer 7 | 8 | #------------------------------ 9 | # Function: iterative_fibonacci 10 | #------------------------------ 11 | @dectimer.bench_time(3) 12 | def iterative_fibonacci(n): 13 | """ 14 | Find the Fibonacci number of order n by iteration 15 | """ 16 | if n < 2: 17 | return n 18 | previous_fibonacci = 1 19 | current_fibonacci = 1 20 | for num in range(2, n): 21 | previous_fibonacci, current_fibonacci = current_fibonacci, \ 22 | current_fibonacci + previous_fibonacci 23 | return current_fibonacci 24 | 25 | #------------------------------ 26 | # Function: recursive_fibonacci 27 | #------------------------------ 28 | @dectimer.bench_time_recursive(3) 29 | def recursive_fibonacci(n): 30 | """ 31 | Find the Fibonacci number of order n by recursion 32 | """ 33 | if n < 2: 34 | return n 35 | else: 36 | return recursive_fibonacci(n-1) + recursive_fibonacci(n-2) 37 | 38 | 39 | if len(sys.argv) < 1: 40 | print('Usage:') 41 | print(' python ' + sys.argv[0] + ' N') 42 | print('Please specify the number of iterations.') 43 | sys.exit() 44 | 45 | N = int(sys.argv[1]) 46 | 47 | print('Fibonacci sequence of size: ', N) 48 | 49 | n1 = iterative_fibonacci(N) 50 | 51 | n2 = recursive_fibonacci(N) 52 | 53 | print(' ') 54 | -------------------------------------------------------------------------------- /Python/test_fibonacci_numba.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | from numba import njit 6 | import sys 7 | import benchmark_decorator as dectimer 8 | 9 | #------------------------------ 10 | # Function: iterative_fibonacci 11 | #------------------------------ 12 | @dectimer.bench_time(3) 13 | @njit 14 | def iterative_fibonacci(n): 15 | """ 16 | Find the Fibonacci number of order n by iteration 17 | """ 18 | if n < 2: 19 | return n 20 | previous_fibonacci = 1 21 | current_fibonacci = 1 22 | for num in range(2, n): 23 | previous_fibonacci, current_fibonacci = current_fibonacci, \ 24 | current_fibonacci + previous_fibonacci 25 | return current_fibonacci 26 | 27 | #------------------------------ 28 | # Function: recursive_fibonacci 29 | #------------------------------ 30 | @dectimer.bench_time_recursive(3) 31 | @njit 32 | def recursive_fibonacci(n): 33 | """ 34 | Find the Fibonacci number of order n by recursion 35 | """ 36 | if n < 2: 37 | return n 38 | else: 39 | return recursive_fibonacci(n-1) + recursive_fibonacci(n-2) 40 | 41 | 42 | if len(sys.argv) < 1: 43 | print('Usage:') 44 | print(' python ' + sys.argv[0] + ' N') 45 | print('Please specify the number of iterations.') 46 | sys.exit() 47 | 48 | N = int(sys.argv[1]) 49 | 50 | print('Numba -- Fibonacci sequence of size: ', N) 51 | 52 | n1 = iterative_fibonacci(N) 53 | 54 | #n2 = recursive_fibonacci(N) 55 | 56 | print(' ') 57 | -------------------------------------------------------------------------------- /Python/test_gauss_legendre_quadrature.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | import numpy as np 6 | import sys 7 | import benchmark_decorator as dectimer 8 | 9 | #-------------------- 10 | # Function: integrand 11 | #-------------------- 12 | integrand = lambda x: np.exp(x) 13 | 14 | #----------------------------- 15 | # Function: compute_quadrature 16 | #----------------------------- 17 | @dectimer.bench_time(3) 18 | def compute_quadrature(n): 19 | """ 20 | Perform the Gauss-Legendre Quadrature at the prescribed order n 21 | """ 22 | a = -3.0 23 | b = 3.0 24 | 25 | # Gauss-Legendre (default interval is [-1, 1]) 26 | x, w = np.polynomial.legendre.leggauss(n) 27 | 28 | # Translate x values from the interval [-1, 1] to [a, b] 29 | t = 0.5*(x + 1)*(b - a) + a 30 | 31 | gauss = sum(w * integrand(t)) * 0.5*(b - a) 32 | 33 | if len(sys.argv) < 1: 34 | print('Usage:') 35 | print(' python ' + sys.argv[0] + ' N') 36 | print('Please specify the order of the quadrature.') 37 | sys.exit() 38 | 39 | order = int(sys.argv[1]) 40 | 41 | print('Gauss-Legendre Quadrature of order: ', order) 42 | 43 | compute_quadrature(order) 44 | 45 | print(' ') 46 | -------------------------------------------------------------------------------- /Python/test_identity_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | 4 | from __future__ import print_function 5 | 6 | import sys 7 | import os 8 | import benchmark_decorator as dectimer 9 | 10 | def reverse_list_strings(lines): 11 | """ 12 | Reverse a list of strings: 13 | 14 | - First, reverse entries of the list. 15 | - Second, reverse each entry of the reversed list. 16 | """ 17 | return [line[::-1] for line in lines[::-1]] 18 | 19 | #-------------------------- 20 | # Function: identity_function_file 21 | #-------------------------- 22 | @dectimer.bench_time(3) 23 | def identity_function_file(file_name): 24 | """ 25 | Read an entire file, complete reverse its content and reverse it back to 26 | obtain the original file content. 27 | """ 28 | # Read the file to get its content as a list of lines. 29 | with open(file_name, "r") as file_id: 30 | lines = file_id.read().splitlines() 31 | 32 | return lines == reverse_list_strings(reverse_list_strings(lines)) 33 | 34 | #rev_file_name = "rev_" + os.path.basename(file_name) 35 | #with open(rev_file_name, "w") as rev_file_id: 36 | # rev_file_id.writelines("%s\n" % line[::-1] for line in lines[::-1]) 37 | #lines = reverse_collection(lines) 38 | #for line in lines: 39 | # rev_file_id.writelines(reverse_collection(line)+"\n") 40 | 41 | if len(sys.argv) < 1: 42 | print('Usage:') 43 | print(' python ' + sys.argv[0] + ' file_name') 44 | print('Please specify the file name') 45 | sys.exit() 46 | 47 | file_name = sys.argv[1] 48 | 49 | identity_function_file(file_name) 50 | -------------------------------------------------------------------------------- /Python/test_look_and_say.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | import sys 6 | import benchmark_decorator as dectimer 7 | 8 | #-------------------------------- 9 | # Function: look_and_say_sequence 10 | #-------------------------------- 11 | @dectimer.bench_time(3) 12 | def look_and_say_sequence(starting_sequence, n): 13 | """ 14 | Construct the look and say sequence of order n and starting 15 | sequence starting_sequence (string) 16 | """ 17 | i = 0 18 | 19 | while i < n: 20 | if i == 0: 21 | current_sequence = starting_sequence 22 | else: 23 | count = 1 24 | temp_sequence = "" 25 | for j in range(1, len(current_sequence)): 26 | if current_sequence[j] == current_sequence[j-1]: 27 | count += 1 28 | else: 29 | temp_sequence = temp_sequence + str(count) \ 30 | + current_sequence[j-1] 31 | count = 1 32 | temp_sequence = temp_sequence + str(count)\ 33 | + current_sequence[len(current_sequence) - 1] 34 | 35 | current_sequence = temp_sequence 36 | i += 1 37 | return current_sequence 38 | 39 | 40 | if len(sys.argv) < 2: 41 | print('Usage:') 42 | print(' python ' + sys.argv[0] + ' N') 43 | print('Please specify a number.') 44 | sys.exit() 45 | 46 | N = int(sys.argv[1]) 47 | 48 | print('Look of say sequence of order: ', N) 49 | 50 | seq = look_and_say_sequence("1223334444", N) 51 | 52 | #print('Sequence of order ', N, ': ', seq) 53 | print(' ') 54 | -------------------------------------------------------------------------------- /Python/test_markov_chain.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | import sys 6 | import numpy as np 7 | import benchmark_decorator as dectimer 8 | 9 | #------------ 10 | # Function: f 11 | #------------ 12 | def f(x): 13 | """ 14 | Math function to use in the algorithm 15 | """ 16 | return np.exp(np.sin(x[0]*5) - x[0]*x[0] - x[1]*x[1]) 17 | 18 | #-------------------------------- 19 | # Function: markov_chain_function 20 | #-------------------------------- 21 | @dectimer.bench_time(3) 22 | def markov_chain_function(n): 23 | """ 24 | Operate the Markov chain n times 25 | """ 26 | x = np.zeros((2)) 27 | p = f(x) 28 | for i in range(n): 29 | x2 = x + .01*np.random.randn(x.size) 30 | p2 = f(x2) 31 | if (np.random.rand() < (p2/p)): 32 | x = x2 33 | p = p2 34 | return x 35 | 36 | if len(sys.argv) < 1: 37 | print('Usage:') 38 | print(' python ' + sys.argv[0] + ' N') 39 | print('Please specify the number of iterations.') 40 | sys.exit() 41 | 42 | N = int(sys.argv[1]) 43 | 44 | print('Markov Chain calculations: ', N) 45 | 46 | y = markov_chain_function(N) 47 | 48 | print(' ') 49 | -------------------------------------------------------------------------------- /Python/test_matrix_multiplication.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | import numpy as np 6 | import sys 7 | import benchmark_decorator as dectimer 8 | 9 | #-------------------------------- 10 | # Function: matrix_multiplication 11 | #-------------------------------- 12 | @dectimer.bench_time(3) 13 | def matrix_multiplication(A, B): 14 | """ 15 | Evaluate the dot product of matrices A and B using numpy 16 | """ 17 | C = np.dot(A, B) 18 | 19 | if len(sys.argv) < 1: 20 | print('Usage:') 21 | print(' python ' + sys.argv[0] + ' N') 22 | print('Please specify matrix dimensions') 23 | sys.exit() 24 | 25 | N = int(sys.argv[1]) 26 | 27 | print('Matrix multiplication: ', N) 28 | 29 | A = np.random.rand(N, N) 30 | B = np.random.rand(N, N) 31 | 32 | matrix_multiplication(A, B) 33 | 34 | print(' ') 35 | -------------------------------------------------------------------------------- /Python/test_matrix_multiplication_numba.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | import numpy as np 6 | import sys 7 | import numba as nb 8 | from numba import njit 9 | from numba import prange 10 | import benchmark_decorator as dectimer 11 | 12 | #-------------------------------- 13 | # Function: matrix_multiplication 14 | #-------------------------------- 15 | @dectimer.bench_time(3) 16 | @njit(parallel=True) 17 | def matrix_multiplication(A, B): 18 | """ 19 | Multiply matrices A and B using a loop 20 | """ 21 | m, n = A.shape 22 | p = B.shape[1] 23 | C = np.zeros((m, p)) 24 | for i in prange(m): 25 | for j in prange(p): 26 | for k in prange(n): 27 | C[i, j] += A[i, k]*B[k, j] 28 | 29 | 30 | if len(sys.argv) < 1: 31 | print('Usage:') 32 | print(' python ' + sys.argv[0] + ' N') 33 | print('Please specify matrix dimensions') 34 | sys.exit() 35 | 36 | N = int(sys.argv[1]) 37 | 38 | print('Numba -- Matrix multiplication (loop): ', N) 39 | 40 | A = np.random.rand(N, N) 41 | B = np.random.rand(N, N) 42 | 43 | matrix_multiplication(A, B) 44 | 45 | print(' ') 46 | -------------------------------------------------------------------------------- /Python/test_munchausen_number.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | import benchmark_decorator as dectimer 6 | 7 | #--------------------------- 8 | # Function: raised_to_string 9 | #--------------------------- 10 | def raised_to_string(x): 11 | """ 12 | Convert to int, then raise the input to the power of itself. 13 | """ 14 | x = int(x) 15 | if x == 0: 16 | return 0 17 | else: 18 | return x**x 19 | 20 | #-------------------- 21 | # Function: raised_to 22 | #-------------------- 23 | def raised_to(x): 24 | """ 25 | Raise the input to the power of itself 26 | """ 27 | if x == 0: 28 | return 0 29 | else: 30 | return x**x 31 | 32 | power_of_digits = [raised_to(i) for i in range(10)] 33 | 34 | #------------------------------- 35 | # Function: is_munchausen_number 36 | #------------------------------- 37 | def is_munchausen_number(i): 38 | return i == sum(power_of_digits[int(x)] for x in str(i)) 39 | 40 | #---------------------------------- 41 | # Function: find_munchausen_numbers 42 | #---------------------------------- 43 | @dectimer.bench_time(3) 44 | def find_munchausen_numbers(): 45 | """ 46 | Find the 4 Munchausen numbers 47 | """ 48 | number = 0 49 | i = 0 50 | while True: 51 | if is_munchausen_number(i): 52 | number += 1 53 | print("Munchausen number %d: %d" % (number, i)) 54 | 55 | if (number == 4): 56 | break 57 | 58 | i += 1 59 | 60 | #-------------------------------------- 61 | # Function: find_munchausen_numbers_map 62 | #-------------------------------------- 63 | @dectimer.bench_time(3) 64 | def find_munchausen_numbers_map(): 65 | """ 66 | Find the 4 Munchausen numbers using map() 67 | """ 68 | num = 0 69 | i = 0 70 | while True: 71 | if i == sum(map(raised_to_string, str(i))): 72 | num += 1 73 | print("Munchausen number %d: %d" %(num, i)) 74 | if (num == 4): 75 | break 76 | i += 1 77 | 78 | find_munchausen_numbers() 79 | #find_munchausen_numbers_map() 80 | -------------------------------------------------------------------------------- /Python/test_pernicious_numbers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Determine the nth pernicious number. 4 | 5 | http://www.rosettacode.org/wiki/Pernicious_numbers 6 | 7 | """ 8 | 9 | from __future__ import print_function 10 | import sys 11 | import benchmark_decorator as dectimer 12 | 13 | def is_prime_number(n): 14 | """ 15 | Deterine if a positive integer is prime or not. 16 | """ 17 | if n in (2, 3): 18 | return True 19 | if 2 > n or 0 == n % 2: 20 | return False 21 | if 9 > n: 22 | return True 23 | if 0 == n % 3: 24 | return False 25 | 26 | return not any(map( 27 | lambda x: 0 == n % x or 0 == n % (2 + x), 28 | range(5, 1 + int(n ** 0.5), 6) 29 | )) 30 | 31 | def get_number_of_ones(n): 32 | """ 33 | Deterine the number of 1s ins the binary representation of 34 | and integer n. 35 | """ 36 | return bin(n).count("1") 37 | 38 | 39 | @dectimer.bench_time(3) 40 | def find_pernicious_numbers(n): 41 | """ 42 | Find the nth pernicious number. 43 | """ 44 | i = 1 45 | counter = 0 46 | while counter < n: 47 | if is_prime_number(get_number_of_ones(i)): 48 | counter += 1 49 | #print(n, counter, i, get_number_of_ones(i)) 50 | i += 1 51 | #print(i-1) 52 | return i-1, counter 53 | 54 | N = int(sys.argv[1]) 55 | find_pernicious_numbers(N) 56 | 57 | #print(vals) 58 | -------------------------------------------------------------------------------- /Python/test_sqrt_matrix.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import print_function 4 | 5 | import numpy as np 6 | import scipy.linalg 7 | import sys 8 | import benchmark_decorator as dectimer 9 | 10 | #---------------------- 11 | # Function: sqrt_matrix 12 | #---------------------- 13 | @dectimer.bench_time(3) 14 | def sqrt_matrix(A): 15 | """ 16 | Take the square root of matrix A 17 | """ 18 | B = scipy.linalg.sqrtm(A) 19 | 20 | n = int(sys.argv[1]) 21 | 22 | print('Square root of matrix: ', n) 23 | 24 | A = np.ones((n, n)) 25 | for i in range(n): 26 | A[i, i] = 6 27 | 28 | sqrt_matrix(A) 29 | 30 | print(' ') 31 | -------------------------------------------------------------------------------- /Python/test_time_series_AOA.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | ############## 4 | # Load modules 5 | ############## 6 | from __future__ import print_function 7 | 8 | import os 9 | from netCDF4 import Dataset 10 | import numpy as np 11 | import glob 12 | import benchmark_decorator as dectimer 13 | 14 | #---------------------------------------- 15 | # Function: serial_time_series_processing 16 | #---------------------------------------- 17 | @dectimer.bench_time(3) 18 | def serial_time_series_processing(): 19 | """ 20 | Do serial time series processing on a collection of files 21 | """ 22 | variable_name = 'aoa' 23 | beginning_year = 1990 24 | end_year = 2009 25 | #end_year = 1990 26 | 27 | first_file = 0 28 | reference_latitude = -86.0 29 | 30 | num_days = 0 31 | 32 | coefficient = 365.5 33 | 34 | reference_directory = '../Data/' 35 | 36 | # Loop over the years 37 | for year in range(beginning_year, end_year+1): 38 | #print('Processing year: %d' % (year)) 39 | directory_name = 'Y'+str(year) 40 | directory_Y = os.path.join(reference_directory, directory_name) 41 | 42 | list_files = glob.glob(directory_Y+"/runAOA.TR."+str(year)+"*_1200z.nc4") 43 | 44 | num_days += len(list_files) 45 | 46 | # Loop over the daily files 47 | for file in list_files: 48 | # Open file 49 | opened_file = Dataset(file, mode='r') 50 | 51 | # Extract information if it is the first file 52 | if first_file == 0: 53 | longitudes = opened_file.variables['lon'][:] 54 | latitudes = opened_file.variables['lat'][:] 55 | #levels = opened_file.variables['lev'][::-1] 56 | num_longitudes = np.size(longitudes) 57 | num_latitudes = np.size(latitudes) 58 | #num_levels = np.size(levels) 59 | 60 | #levels = pressLevels.calcPressureLevels(num_levels) 61 | latitude_index = (np.abs(latitudes - reference_latitude)).argmin() 62 | #print("Latitude index: ", latitude_index) 63 | 64 | # Read the daily average age of air 65 | age_air = opened_file.variables[variable_name][0, ::-1, latitude_index, :] / coefficient 66 | 67 | # Determine the zonal mean 68 | zonal_mean = np.mean(age_air, axis=1) 69 | 70 | # Stack the daily values into an existing array 71 | if first_file == 0: 72 | first_file = 1 73 | data_value = zonal_mean 74 | else: 75 | data_value = np.column_stack((data_value, zonal_mean)) 76 | 77 | # Close file 78 | opened_file.close() 79 | 80 | 81 | serial_time_series_processing() 82 | 83 | print(' ') 84 | -------------------------------------------------------------------------------- /Python/test_time_series_AOA_multiproc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | ############## 4 | # Load modules 5 | ############## 6 | from __future__ import print_function 7 | 8 | import os 9 | import sys 10 | from netCDF4 import Dataset 11 | import numpy as np 12 | import glob 13 | import multiprocessing 14 | import benchmark_decorator as dectimer 15 | 16 | #----------------------------- 17 | # Function: get_data_from_file 18 | #----------------------------- 19 | def get_data_from_file(file_name): 20 | """ 21 | Read the data from file 22 | """ 23 | v_name = 'aoa' 24 | reference_latitude = -86.0 25 | 26 | coefficient = 365.5 27 | 28 | opened_file = Dataset(file_name, mode='r') 29 | 30 | latitudes = opened_file.variables['lat'][:] 31 | 32 | latitude_index = (np.abs(latitudes - reference_latitude)).argmin() 33 | 34 | # Read the daily average age of air 35 | age_air = opened_file.variables[v_name][0, ::-1, latitude_index, :] / coefficient 36 | 37 | # Determine the zonal mean to be returned 38 | data_value = np.mean(age_air, axis=1) 39 | 40 | # Close file 41 | opened_file.close() 42 | 43 | return data_value 44 | 45 | #------------------------------------------ 46 | # Function: parallel_time_series_processing 47 | #------------------------------------------ 48 | @dectimer.bench_time(3) 49 | def parallel_time_series_processing(num_threads): 50 | """ 51 | Do parallel time series processing on a collection of files 52 | """ 53 | 54 | beginning_year = 1990 55 | end_year = 2009 56 | num_days = 0 57 | my_list = [] 58 | 59 | reference_directory = '../Data/' 60 | 61 | # Loop over the years 62 | for year in range(beginning_year, end_year+1): 63 | directory_name = 'Y'+str(year) 64 | directory_Y = os.path.join(reference_directory, directory_name) 65 | 66 | list_files = glob.glob(directory_Y + "/runAOA.TR." + str(year) + 67 | "*_1200z.nc4") 68 | 69 | num_days += len(list_files) 70 | 71 | my_pool = multiprocessing.Pool(num_threads) 72 | my_array = my_pool.map(get_data_from_file, list_files) 73 | 74 | my_pool.close() 75 | my_pool.terminate() 76 | 77 | my_list.extend(my_array) 78 | 79 | num_threads = int(sys.argv[1]) 80 | 81 | print("-------------------------------") 82 | print("Number of threads used: ", num_threads) 83 | print("-------------------------------") 84 | 85 | parallel_time_series_processing(num_threads) 86 | 87 | print(' ') 88 | -------------------------------------------------------------------------------- /R/.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/.RData -------------------------------------------------------------------------------- /R/.Rhistory: -------------------------------------------------------------------------------- 1 | install.packages("gaussquad", lib=/gpfsm/dnb32/jkouatch/LearningPython/compareLanguages/refSourceFiles/R") 2 | install.packages("gaussquad", lib="/gpfsm/dnb32/jkouatch/LearningPython/compareLanguages/refSourceFiles/R") 3 | exit 4 | quit 5 | exit() 6 | quit() 7 | install.packages("pracma", lib="/gpfsm/dnb32/jkouatch/LearningPython/compareLanguages/refSourceFiles/R") 8 | quit() 9 | install.packages("pracma", lib="/gpfsm/dnb32/jkouatch/LearningPython/compareLanguages/refSourceFiles/R/locPACKAGES") 10 | install.packages("rbenchmark", lib="/gpfsm/dnb32/jkouatch/LearningPython/compareLanguages/refSourceFiles/R/locPACKAGES") 11 | install.packages("microbenchmark", lib="/gpfsm/dnb32/jkouatch/LearningPython/compareLanguages/refSourceFiles/R/locPACKAGES") 12 | quit() 13 | m = 1542 14 | digits <- floor(m / 10^(0:(nchar(m) - 1))) %% 10 15 | digits 16 | nchar(m) 17 | m / 10^(0:(nchar(m) - 1)) 18 | floor(m / 10^(0:(nchar(m) - 1))) 19 | -------------------------------------------------------------------------------- /R/._.Rhistory: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._.Rhistory -------------------------------------------------------------------------------- /R/._rJobScript.job: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._rJobScript.job -------------------------------------------------------------------------------- /R/._solver_order_4.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._solver_order_4.R -------------------------------------------------------------------------------- /R/._test_belief_propagation.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_belief_propagation.R -------------------------------------------------------------------------------- /R/._test_compute_FFT.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_compute_FFT.R -------------------------------------------------------------------------------- /R/._test_copy_matrix.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_copy_matrix.R -------------------------------------------------------------------------------- /R/._test_count_unique_words.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_count_unique_words.R -------------------------------------------------------------------------------- /R/._test_evaluate_functions.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_evaluate_functions.R -------------------------------------------------------------------------------- /R/._test_fibonacci.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_fibonacci.R -------------------------------------------------------------------------------- /R/._test_gauss_legendre_quadrature.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_gauss_legendre_quadrature.R -------------------------------------------------------------------------------- /R/._test_get_data_from_file.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_get_data_from_file.R -------------------------------------------------------------------------------- /R/._test_get_levels.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_get_levels.R -------------------------------------------------------------------------------- /R/._test_laplace_jacobi_4.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_laplace_jacobi_4.R -------------------------------------------------------------------------------- /R/._test_look_and_say.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_look_and_say.R -------------------------------------------------------------------------------- /R/._test_markov_chain.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_markov_chain.R -------------------------------------------------------------------------------- /R/._test_matrix_multiplication.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_matrix_multiplication.R -------------------------------------------------------------------------------- /R/._test_munchausen_number.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_munchausen_number.R -------------------------------------------------------------------------------- /R/._test_sqrt_matrix.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_sqrt_matrix.R -------------------------------------------------------------------------------- /R/._test_time_series_AOA.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_time_series_AOA.R -------------------------------------------------------------------------------- /R/._test_time_series_AOA_multiproc.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._test_time_series_AOA_multiproc.R -------------------------------------------------------------------------------- /R/._vertLevels_GEOS5.R: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/R/._vertLevels_GEOS5.R -------------------------------------------------------------------------------- /R/solver_order_4.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | 4 | RegularTimeStepij <- function(u) { 5 | # Take a time step in the desired numerical solution u found using loops over j for each i. 6 | # 7 | # Args: 8 | # u: Numerical values of the approximated solution. 9 | # 10 | # Returns: 11 | # output: The numerical solution value and error value. 12 | n <- dim(u)[1] - 1 13 | m <- dim(u)[2] - 1 14 | error <- 0.0 15 | for (i in 2:n) { 16 | for (j in 2:m) { 17 | temp <- u[i,j] 18 | u[i,j] <- ( ((u[i-1,j] + u[i+1,j] + u[i,j-1] + u[i,j+1])*4.0 + 19 | u[i-1,j-1] + u[i-1,j+1] + u[i+1,j-1] + u[i+1,j+1])/20.0 ) 20 | 21 | difference <- u[i,j] - temp 22 | error <- error + difference*difference 23 | } 24 | } 25 | output <- list("u"=u, "error"=sqrt(error)) 26 | return(output) 27 | } 28 | 29 | 30 | RegularTimeStepji <- function(u) { 31 | # Take a time step in the desired numerical solution u found using loops over i for each j. 32 | # 33 | # Args: 34 | # u: Numerical values of the approximated solution. 35 | # 36 | # Returns: 37 | # output: The numerical solution value and error value. 38 | n <- dim(u)[1] - 1 39 | m <- dim(u)[2] - 1 40 | error <- 0.0 41 | for (j in 2:m){ 42 | for (i in 2:n){ 43 | temp <- u[i,j] 44 | u[i,j] <- (((u[i-1,j] + u[i+1,j] + u[i,j-1] + u[i,j+1])*4.0 + 45 | u[i-1,j-1] + u[i-1,j+1] + u[i+1,j-1] + u[i+1,j+1])/20.0 ) 46 | 47 | difference <- u[i,j] - temp 48 | error <- error + difference*difference 49 | } 50 | } 51 | output <- list("u"=u, "error"=sqrt(error)) 52 | return(output) 53 | } 54 | 55 | 56 | VectorizedTimeStep <- function(u) { 57 | # Take a time step in the desired numerical solution u found using vectorization. 58 | # 59 | # Args: 60 | # u: Numerical values of the approximated solution. 61 | # 62 | # Returns: 63 | # output: The numerical solution value and error value. 64 | n <- dim(u)[1] 65 | m <- dim(u)[2] 66 | u.old <- u 67 | 68 | n1 <- n-1 69 | n3 <- n-2 70 | 71 | m1 <- m-1 72 | m3 <- m-2 73 | 74 | u[2:n1, 2:m1] <- (((u[1:n3, 2:m1] + u[3:n, 2:m1] + 75 | u[2:n1, 1:m3] + u[2:n1, 3:m])*4.0 + 76 | u[1:n3, 1:m3] + u[1:n3, 3:m] + 77 | u[3:n, 1:m3] + u[3:n, 3:m])/20.0 ) 78 | 79 | v <- as.vector(u - u.old) 80 | error = v%*%v 81 | output <- list("u"=u, "error"=sqrt(error[1])) 82 | 83 | return(output) 84 | } 85 | 86 | -------------------------------------------------------------------------------- /R/test_belief_propagation.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | library(rbenchmark) 4 | 5 | 6 | arguments = commandArgs(TRUE) 7 | 8 | 9 | # Get the number of iterations n from the command line. 10 | if (length(arguments) == 0) { 11 | stop("At least one argument must be supplied (numIterations).n", call.=FALSE) 12 | } else if (length(arguments) == 1) { 13 | n <- as.integer(arguments[1]) 14 | } 15 | 16 | BeliefPropagation <- function(A, x, N) { 17 | # Run the belief propagation algorithm for a given number of iterations. 18 | # 19 | # Args: 20 | # A: An m by m matrix of random values. 21 | # x: An m by 1 matrix of 1.0 values. 22 | # N: Integer number of iterations. 23 | # 24 | # Returns: 25 | # x: m by 1 matrix after operating the belief propagation algorithm. 26 | for (i in 1:N) { 27 | x2 <- log(A %*% exp(x)) 28 | x <- x - log(sum(exp(x2))) 29 | } 30 | return(x) 31 | } 32 | 33 | 34 | cat('---------------------------------------\n') 35 | cat(' Belief Calculations: ', n, '\n') 36 | cat('---------------------------------------\n') 37 | 38 | benchmark("Belief" = { 39 | m <- 5000 40 | A <- matrix(runif(m*m), m) 41 | x <- matrix(1.0, nrow=m, ncol=1) 42 | y <- BeliefPropagation(A, x, n) 43 | }, 44 | replications = 1, 45 | columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self")) 46 | -------------------------------------------------------------------------------- /R/test_compute_FFT.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | library(rbenchmark) 4 | 5 | 6 | args = commandArgs(TRUE) 7 | 8 | # Get the number of iterations n from the command line. 9 | if (length(args) == 0) { 10 | stop("At least one argument must be supplied (dimension).n", call.=FALSE) 11 | } else if (length(args) == 1) { 12 | n <- as.integer(args[1]) 13 | } 14 | 15 | cat('-----------------------------------------\n') 16 | cat(' Compute FFT: ', n, '\n') 17 | cat('-----------------------------------------\n') 18 | 19 | # Determine the time taken to find the FFT of the matrix of values. 20 | benchmark("FFT" = { 21 | matrix <- array(rnorm(n*n), dim=c(n, n)) + 1i*array(rnorm(n*n), dim=c(n, n)) 22 | result <- fft(matrix) 23 | result <- abs(result) 24 | }, 25 | replications = 1, 26 | columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self")) 27 | 28 | -------------------------------------------------------------------------------- /R/test_copy_matrix.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | library(rbenchmark) 4 | 5 | 6 | arguments = commandArgs(TRUE) 7 | 8 | # Get the matrix dimensions n from the command line. 9 | if (length(arguments) == 0) { 10 | stop("At least one argument must be supplied (dimension).n", call.=FALSE) 11 | } else if (length(arguments) == 1) { 12 | n <- as.integer(arguments[1]) 13 | } 14 | 15 | cat('-----------------------------------------\n') 16 | cat(' Copy Matrix: ', n, '\n') 17 | cat('-----------------------------------------\n') 18 | 19 | A <- array(rnorm(n*n*3), dim=c(n, n, 3)) 20 | B <- array(rnorm(n*n*3), dim=c(n, n, 3)) 21 | 22 | # Determine the time to perform several copy operations on the matrices. 23 | benchmark("Loop" = { 24 | for (j in 1:n) { 25 | for (i in 1:n){ 26 | A[i, j, 1] <- A[i, j, 2] 27 | A[i, j, 3] <- A[i, j, 1] 28 | A[i, j, 2] <- A[i, j, 3] 29 | } 30 | } 31 | }, 32 | "Vectorization" = { 33 | B[, , 1] <- B[, , 2] 34 | B[, , 3] <- B[, , 1] 35 | B[, , 2] <- B[, , 3] 36 | }, 37 | replications = 1, 38 | columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self")) 39 | -------------------------------------------------------------------------------- /R/test_count_unique_words.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | library(rbenchmark) 4 | 5 | arguments = commandArgs(TRUE) 6 | 7 | # Get the filename 'name' from the command line. 8 | if (length(arguments) == 0) { 9 | stop("At least one argument must be supplied (name of file).n", call.=FALSE) 10 | } else if (length(arguments) == 1) { 11 | #name <- as.string(arguments[1]) 12 | name <- arguments[1] 13 | } 14 | 15 | cat('-----------------------------------------\n') 16 | cat(' Count the number of unique words in: ', name, '\n') 17 | cat('-----------------------------------------\n') 18 | 19 | CountWords <- function(filename, return.an.int=FALSE) { 20 | # Count the number of unique words in the given file. 21 | # 22 | # Args: 23 | # filename: The name of the file to read, including its file extension. 24 | file.id <- file(filename, open="r") 25 | lines <- readLines(file.id) 26 | close(file.id) 27 | unique.words <- c() 28 | for (i in 1:length(lines)) { 29 | unique.words <- union(unique.words, tolower(strsplit(gsub("[^[:alpha:] ]", "", lines[i]), " +")[[1]])) 30 | } 31 | #unique.words <- unique(tolower(unique.words)) 32 | } 33 | 34 | benchmark("Count Words" = { 35 | n <- CountWords(name) 36 | }, 37 | replications = 1, 38 | columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self")) 39 | -------------------------------------------------------------------------------- /R/test_evaluate_functions.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | library(rbenchmark) 4 | 5 | 6 | args = commandArgs(TRUE) 7 | 8 | # Get the number n of evenly-spaced matrix elements from the command line. 9 | if (length(args) == 0) { 10 | stop("At least one argument must be supplied (dimension).n", call.=FALSE) 11 | } else if (length(args) == 1) { 12 | n <- as.integer(args[1]) 13 | } 14 | 15 | cat('-----------------------------------------\n') 16 | cat(' Evaluate Functions: ', n, '\n') 17 | cat('-----------------------------------------\n') 18 | 19 | # Evaluate the trigonometric functions a total of M times each on the matrix of 20 | # n values spaced evenly from -1500.0 to 1500.0. 21 | benchmark("Evaluate" = { 22 | M <- 10000 23 | x <- seq(from=-1500.0, to=1500.0, length.out=n) 24 | for (i in 1:M) { 25 | y <- sin(x) 26 | x <- asin(y) 27 | y <- cos(x) 28 | x <- acos(y) 29 | y <- tan(x) 30 | x <- atan(y) 31 | } 32 | }, 33 | replications = 1, 34 | columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self")) 35 | -------------------------------------------------------------------------------- /R/test_fibonacci.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | library(rbenchmark) 4 | 5 | 6 | args = commandArgs(TRUE) 7 | 8 | # Get the order n of the Fibonacci number to find from the command line. 9 | if (length(args) == 0) { 10 | stop("At least one argument must be supplied (dimension).n", call.=FALSE) 11 | } else if (length(args) == 1) { 12 | n <- as.integer(args[1]) 13 | } 14 | 15 | # Recursive function 16 | #RecursiveFibonacci <- function(n) { 17 | # if ( n < 2 ) n 18 | # else recursiveFobonacci(n-1) + recursiveFobonacci(n-2) 19 | # #else Recall(n-1) + Recall(n-2) 20 | #} 21 | 22 | 23 | RecursiveFibonacci <- function(n) { 24 | # Recursively calculate the Fibonacci number by calling LowerFibonacci. 25 | # 26 | # Args: 27 | # n: The order of Fibonacci number to be found. 28 | LowerOrder <- function(n, minus.1, minus.2) { 29 | # Find Fibonacci numbers of lower orders n-1 and n-2 recursively. 30 | # 31 | # Args: 32 | # n: The order of the desired Fibonacci number. 33 | # minus.1: Fibonacci number of order n-1. Has a minimum of 1. 34 | # minus.2: Fibonacci number of order n-2. Has a minimum of 0. 35 | ifelse(n <= 1, minus.2, 36 | ifelse(n == 2, minus.1, 37 | Recall(n-1, minus.1+minus.2, minus.1) 38 | )) 39 | } 40 | LowerOrder(n, 1, 0) 41 | } 42 | 43 | 44 | IterativeFibonacci <- function(n) { 45 | # Iteratively calculate the desired Fibonacci number by adding up from 0 and 1. 46 | # 47 | # Args: 48 | # n: The order of Fibonacci number to be found. 49 | if (n < 2) 50 | n 51 | else { 52 | fibonacci.number <- c(0, 1) 53 | for (i in 2:n) { 54 | temp <- fibonacci.number[2] 55 | fibonacci.number[2] <- sum(fibonacci.number) 56 | fibonacci.number[1] <- temp 57 | } 58 | fibonacci.number[2] 59 | } 60 | } 61 | 62 | cat('-----------------------------------------\n') 63 | cat(' Fibonacci: ', n, '\n') 64 | cat('-----------------------------------------\n') 65 | 66 | benchmark("Iterative" = {IterativeFibonacci(n)}, 67 | "Recursive" = {RecursiveFibonacci(n)}, 68 | replications = 1, 69 | columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self")) 70 | -------------------------------------------------------------------------------- /R/test_gauss_legendre_quadrature.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | library(pracma) 4 | library(rbenchmark) 5 | 6 | 7 | args = commandArgs(TRUE) 8 | 9 | # Get the number of iterations n from the command line. 10 | if (length(args) == 0) { 11 | stop("At least one argument must be supplied (numIterations).n", call.=FALSE) 12 | } else if (length(args) == 1) { 13 | n <- as.integer(args[1]) 14 | } 15 | 16 | #Integrand f(x) to be numerically integrated. 17 | f <- function(x) exp(x) 18 | 19 | cat('---------------------------------------\n') 20 | cat(' Gauss Legendre Quadrature: ', n, '\n') 21 | cat('---------------------------------------\n') 22 | 23 | #Use Gauss-Legendre quadrature over the interval [a, b] on f(x). 24 | benchmark("Quadrature" = { 25 | a <- -3.0 26 | b <- 3.0 27 | i <- 1:n 28 | x <- a + (i-1)*(b-a)/(n-1) 29 | 30 | quadrature.values <- gaussLegendre(n, a, b) 31 | quadrature.result <- sum(quadrature.values$w*f(quadrature.values$x)) 32 | }, 33 | replications = 1, 34 | columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self")) 35 | 36 | -------------------------------------------------------------------------------- /R/test_get_data_from_file.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | #import packages 4 | #--------------- 5 | library(ncdf4) 6 | 7 | 8 | GetDataFromFile <- function(fileName) { 9 | # Count the number of unique words in the given file. 10 | # 11 | # Args: 12 | # filename: The name of the file to read, including its file extension. 13 | # return.an.int: 14 | coef <- 365.5 15 | set_lat = -86.0 16 | 17 | nf <- nc_open(fileName) 18 | 19 | lats <- ncvar_get(nf, "lat") 20 | LatStartIdx <- which( nf$dim$lat$vals == set_lat) 21 | # Read the daily average age of air at latitute set_lat 22 | #------------------------------------------------------ 23 | var <- ncvar_get(nf, vName)[, LatStartIdx,] / coef # 24 | 25 | # Determine the zonal mean 26 | #------------------------- 27 | tempVar <- apply(var, c(2), mean) 28 | tempVar <- rev(tempVar) # reverse the vertical levels 29 | 30 | nc_close(nf) 31 | 32 | return(tempVar) 33 | 34 | } 35 | -------------------------------------------------------------------------------- /R/test_get_levels.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | #import packages 4 | library(ncdf4) 5 | 6 | source("vertLevels_GEOS5.R") 7 | 8 | getLevels <- function(fileName) { 9 | 10 | nf <- nc_open(fileName) 11 | levs <- ncvar_get(nf, "lev") 12 | nlevs <- dim(levs) 13 | nc_close(nf) 14 | 15 | levs <- calcPressureLevels(nlevs) 16 | 17 | return(levs) 18 | 19 | } 20 | -------------------------------------------------------------------------------- /R/test_look_and_say.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | library(rbenchmark) 4 | 5 | args = commandArgs(TRUE) 6 | 7 | # Get the order n of the look and say sequence from the command line. 8 | if (length(args) == 0) { 9 | stop("At least one argument must be supplied (dimension).n", call.=FALSE) 10 | } else if (length(args) == 1) { 11 | n <- as.integer(args[1]) 12 | } 13 | 14 | LookAndSaySequence <- function(start.sequence.integer, return.an.int=FALSE) { 15 | # Determine the look and say sequence of a given order, starting with the string x. 16 | # 17 | # Args: 18 | # start.sequence.integer: The initial sequence of integers used to find the nth look and say sequence. 19 | # return.an.int: If TRUE, convert the result to an integer. Otherwise, the result is a string. 20 | # 21 | # Returns: 22 | # new.string: The completed look and say sequence of order n as a string or an integer, given return.an.int. 23 | sequence.string <- unlist(strsplit(as.character(start.sequence.integer), "")) 24 | rle.sequence.string <- rle(sequence.string) # Get run length encoding. 25 | 26 | #Form new string. 27 | odds <- as.character(rle.sequence.string$lengths) 28 | evens <- rle.sequence.string$values 29 | new.string <- as.vector(rbind(odds, evens)) 30 | 31 | new.string <- paste(new.string, collapse="") # Collapse to scalar. 32 | if (return.an.int) as.integer(new.string) else new.string # Convert to number, if desired. 33 | } 34 | 35 | 36 | cat('-----------------------------------------\n') 37 | cat(' Look and say sequence of order: ', n, '\n') 38 | cat('-----------------------------------------\n') 39 | 40 | benchmark("Look_and_Say" = { 41 | x <- 1223334444 42 | if (n > 1) { 43 | for (i in 2:n) { 44 | x <- LookAndSaySequence(x) 45 | #print(x) 46 | } 47 | } 48 | }, 49 | replications = 1, 50 | columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self")) 51 | -------------------------------------------------------------------------------- /R/test_markov_chain.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | library(rbenchmark) 4 | 5 | 6 | args = commandArgs(TRUE) 7 | 8 | # Get the number of iterations n from the command line. 9 | if (length(args) == 0) { 10 | stop("At least one argument must be supplied (num.iterations).n", call.=FALSE) 11 | } else if (length(args) == 1) { 12 | n <- as.integer(args[1]) 13 | } 14 | 15 | f <- function(x) { 16 | # Math function f(x) to use in the algorithm. 17 | # 18 | # Args: 19 | # x: Matrix of values to plug in for the function's independent variable. 20 | # 21 | # Returns: 22 | # The input matrix after several operations. 23 | return (exp(sin(x[1]*5) - x[1]*x[1] - x[2]*x[2])) 24 | } 25 | 26 | MarkovChain <- function(x, N) { 27 | # Run the Markov Chain algorithm on the input matrix a given number of times. 28 | # 29 | # Args: 30 | # x: Matrix of values to plug in for the independent variable. 31 | # N: The number of iterations to run the algorithm. 32 | # 33 | # Returns: 34 | # x: The input matrix after being modified by the algorithm a total of N times. 35 | p <- f(x) 36 | for (i in 1:N) { 37 | x2 <- x + 0.01*rnorm(length(x)) 38 | p2 <- f(x2) 39 | if (runif(1) < (p2/p)) { 40 | x <- x2 41 | p <- p2 42 | } 43 | } 44 | return(x) 45 | } 46 | 47 | cat('---------------------------------------\n') 48 | cat(' Markov Chain Calculations: ', n, '\n') 49 | cat('---------------------------------------\n') 50 | 51 | benchmark("Markov Calcs" = { 52 | x <- matrix(0.0, nrow=2, ncol=1) 53 | MarkovChain(x, n) 54 | }, 55 | replications = 1, 56 | columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self")) 57 | -------------------------------------------------------------------------------- /R/test_matrix_multiplication.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | library(rbenchmark) 4 | 5 | 6 | args = commandArgs(TRUE) 7 | 8 | # Get the matrix dimensions n from the command line. 9 | if (length(args) == 0) { 10 | stop("At least one argument must be supplied (dimension).n", call.=FALSE) 11 | } else if (length(args) == 1) { 12 | n <- as.integer(args[1]) 13 | } 14 | 15 | cat('---------------------------------------\n') 16 | cat(' Multiplication of matrices: ', n, '\n') 17 | cat('---------------------------------------\n') 18 | 19 | # Create randomly populated n by n matrices. 20 | A <- matrix(rnorm(n*n), n) 21 | B <- matrix(rnorm(n*n), n) 22 | 23 | # Multiply the two matrices. 24 | benchmark("MatMult" = { C <- A %*% B }, 25 | replications = 1, 26 | columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self")) 27 | -------------------------------------------------------------------------------- /R/test_munchausen_number.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | library(rbenchmark) 4 | 5 | 6 | raisedto <- function(n) { 7 | # Raise the input number to the power of itself. 8 | # 9 | # Args: 10 | # n: Integer value 11 | # 12 | # Returns: 13 | # The resulting number of n raised to its own power. If n is 0, return 0. 14 | if (n == 0) { 15 | return(n) 16 | } else { 17 | return(n^n) 18 | } 19 | } 20 | 21 | 22 | MunchausenNumber <- function(m) { 23 | # Perform the Munchausen number algorithm. 24 | # 25 | # Args: 26 | # m: The number to check. 27 | # 28 | # Returns: 29 | # The number resulting from the Munchausen number alorithm. 30 | #n <- m 31 | digits <- floor(m / 10^(0:(nchar(m) - 1))) %% 10 32 | return(sum(raisedto(digits))) 33 | } 34 | 35 | 36 | FindMunchausenNumbers <- function() { 37 | # Find the four Munchausen numbers. 38 | i <- 0 39 | num <- 0 40 | while (num < 4) { 41 | if (i == MunchausenNumber(i)) { 42 | num <- num + 1 43 | cat("Munchausen Number ", num, ":", i, '\n') 44 | } 45 | i <- i + 1 46 | } 47 | } 48 | 49 | 50 | cat('---------------------------------------------\n') 51 | cat(' Determine the first four Munchausen numbers \n') 52 | cat('---------------------------------------------\n') 53 | 54 | benchmark("FindMunchausenNumbers" = { FindMunchausenNumbers() }, 55 | replications = 1, 56 | columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self")) 57 | -------------------------------------------------------------------------------- /R/test_pernicious_numbers.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | library(rbenchmark) 4 | library(binaryLogic) 5 | library(stringr) 6 | 7 | args = commandArgs(TRUE) 8 | 9 | # Get the number num of the Pernicious numbers to find from the command line. 10 | if (length(args) == 0) { 11 | stop("At least one argument must be supplied n", call.=FALSE) 12 | } else if (length(args) == 1) { 13 | num <- as.integer(args[1]) 14 | } 15 | 16 | 17 | get_number_of_ones <- function(n) { 18 | # Find the number of ones in the binary representation of a number. 19 | # 20 | # Args: 21 | # n: Integer value 22 | # 23 | # Returns: 24 | # The number of ones. 25 | n_bin <- as.binary(n) 26 | n_str <- toString(n_bin) 27 | count_ones <- sum(str_count(n_str, "1")) 28 | return(count_ones) 29 | } 30 | 31 | 32 | is_prime_number <- function(m) { 33 | # Determine if a number is a prime. 34 | # 35 | # Args: 36 | # m: The number to check. 37 | # 38 | # Returns: 39 | # True/False 40 | flag = FALSE 41 | if (m < 2) { 42 | flag = FALSE 43 | } else if (m == 2) { 44 | flag = TRUE 45 | } else if (any(m %% 2:(m-1) == 0)) { 46 | flag = FALSE 47 | } else { 48 | flag = TRUE 49 | } 50 | 51 | return(flag) 52 | } 53 | 54 | 55 | find_pernicious_numbers <- function(n) { 56 | # Find the first n pernicoius numbers. 57 | i <- 1 58 | counter <- 0 59 | while (counter < n) { 60 | if (is_prime_number(get_number_of_ones(i))) { 61 | counter <- counter + 1 62 | #cat("Pernicious ", n, ":", counter, i, get_number_of_ones(i), '\n') 63 | } 64 | i <- i + 1 65 | } 66 | return(i-1) 67 | } 68 | 69 | 70 | cat('---------------------------------------------\n') 71 | cat(' Determine the Pernicious numbers \n') 72 | cat('---------------------------------------------\n') 73 | 74 | benchmark("find_pernicious_numbers" = { find_pernicious_numbers(num) }, 75 | replications = 1, 76 | columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self")) 77 | -------------------------------------------------------------------------------- /R/test_sqrt_matrix.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | library(rbenchmark) 4 | 5 | 6 | args = commandArgs(TRUE) 7 | 8 | # Get the dimension n of the matrix. 9 | if (length(args) == 0) { 10 | stop("At least one argument must be supplied (dimension).n", call.=FALSE) 11 | } else if (length(args) == 1) { 12 | n <- as.integer(args[1]) 13 | } 14 | 15 | "%^%" <- function(S, power) 16 | # Raise the matrix to the given power. 17 | # 18 | # Args: 19 | # S: Matrix to raise to a power. 20 | # power: The power to which the matrix is raised. 21 | # 22 | # Returns: 23 | # The matrix after being raised to the power. 24 | with(eigen(S), vectors %*% (values^power*t(vectors))) 25 | 26 | 27 | cat('-----------------------------------------\n') 28 | cat(' Square root of matrix: ', n, '\n') 29 | cat('-----------------------------------------\n') 30 | 31 | #A <- matrix(1, n, n) 32 | A <- array(1, dim=c(n,n)) 33 | for (i in 1:n) { 34 | A[i,i] <- 6 35 | } 36 | 37 | benchmark("sqrtMat" = { B <- A%^%(0.5) }, 38 | replications = 1, 39 | columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self")) 40 | -------------------------------------------------------------------------------- /R/vertLevels_GEOS5.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | 3 | calcPressureLevels <- function(nlevs) { 4 | # """ 5 | # This function takes the number of vertical levels 6 | # to read a file that contains the values of ak and bk. 7 | # It then computes the pressure levels using the formula: 8 | # 9 | # 0.5*(ak[l]+ak[l+1]) + 0.1*1.0e5*(bk[l]+bk[l+1]) 10 | # 11 | # Input Varialble: 12 | # nlevs: number of vertical levels 13 | # 14 | # Returned Value: 15 | # phPa: pressure levels from bottom to top 16 | # """ 17 | ak <- array(0.0, dim=c(nlevs+1)) 18 | bk <- array(0.0, dim=c(nlevs+1)) 19 | phPa <- array(0.0, dim=c(nlevs)) 20 | 21 | fileName <- paste(toString(nlevs),'-layer.p', sep='') 22 | 23 | fid <- read.table(fileName, skip=2) 24 | for (k in 0:nlevs+1) { 25 | ak[k] <- fid[k,2] 26 | bk[k] <- fid[k,3] 27 | } 28 | 29 | for (k in 1:nlevs) { 30 | phPa[k] <- 0.50*((ak[k]+ak[k+1])+0.01*1.00e+05*(bk[k]+bk[k+1])) 31 | } 32 | 33 | return(rev(phPa)) 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Scala/DoBeliefPropagation.scala: -------------------------------------------------------------------------------- 1 | import Array._ 2 | import math._ 3 | 4 | object DoBeliefPropagation { 5 | def main(args: Array[String]): Unit = { 6 | 7 | object Matrix{ 8 | def apply( rowCount:Int, colCount:Int )( f:(Int,Int) => Float ) = ( 9 | for(i <- 1 to rowCount) yield 10 | ( for( j <- 1 to colCount) yield f(i,j) ).toList 11 | ).toList 12 | } 13 | 14 | if (args.length == 0) { 15 | println("Need to provide matrix dimension") 16 | } 17 | val N = args(0).toInt; 18 | 19 | val dim = 5000; 20 | // val N = 250; 21 | 22 | var elapsedTime: Long = 0; 23 | 24 | val r = scala.util.Random; 25 | 26 | // Array declarations 27 | //------------------- 28 | 29 | var A = ofDim[Double](dim,dim); 30 | var x = ofDim[Double](dim); 31 | var x2 = ofDim[Double](dim); 32 | 33 | var mysum : Double = 0; 34 | var mynorm : Double = 0; 35 | 36 | var i = 1; 37 | var j = 1; 38 | var k = 1; 39 | 40 | var startTime = System.currentTimeMillis 41 | 42 | // build a matrix 43 | for (i <- 0 to dim-1) { 44 | x(i) = 0; 45 | for ( j <- 0 to dim-1) { 46 | A(i)(j) = r.nextDouble; 47 | } 48 | } 49 | 50 | println("-----------------------------") ; 51 | println("Perform belief calculations "+N) ; 52 | println("-----------------------------") ; 53 | 54 | 55 | // Perform the matrix multiplcation 56 | //--------------------------------- 57 | 58 | for (k <- 0 to N-1) { 59 | for (i <- 0 to dim-1) { 60 | x2(i) = 0; 61 | for (j <- 0 to dim-1) { 62 | x2(i) = x2(i) + A(i)(j)*scala.math.exp(x(j)); 63 | } 64 | } 65 | 66 | for (i <- 0 to dim-1) { 67 | x(i) = scala.math.log(x2(i)); 68 | } 69 | 70 | mysum = 0; 71 | for (i <- 0 to dim-1) { 72 | mysum = mysum + scala.math.exp(x(i)); 73 | } 74 | 75 | mynorm = scala.math.log(mysum); 76 | for (i <- 0 to dim-1) { 77 | x(i) = x(i) - mynorm; 78 | } 79 | 80 | 81 | } 82 | var stopTime = System.currentTimeMillis 83 | 84 | println("Elapsed time (s): " + (stopTime-startTime)/1000.0) 85 | println("Done with belief computations") 86 | println("-------------------------------") 87 | } 88 | } 89 | 90 | -------------------------------------------------------------------------------- /Scala/DoBelief_jama.scala: -------------------------------------------------------------------------------- 1 | import Array._ 2 | import math._ 3 | import Jama._ 4 | 5 | object DoBelief_jama { 6 | def main(args: Array[String]): Unit = { 7 | 8 | if (args.length == 0) { 9 | println("Need to provide matrix dimension") 10 | } 11 | val N = args(0).toInt; 12 | 13 | val dim = 5000; 14 | // val N = 250; 15 | 16 | var elapsedTime: Long = 0; 17 | 18 | // Create the matrix 19 | val A = new Matrix(dim, dim) 20 | 21 | var startTime = System.currentTimeMillis 22 | 23 | // Fill the matrix with random numbers 24 | val r = new scala.util.Random(0) 25 | 26 | for(i <- 0 until A.getRowDimension()) 27 | for(j <- 0 until A.getColumnDimension()) 28 | A.set(i, j, r.nextDouble()) 29 | 30 | var x = ofDim[Double](dim); 31 | var x2 = ofDim[Double](dim); 32 | 33 | var mysum : Double = 0; 34 | var mynorm : Double = 0; 35 | 36 | var i = 1; 37 | var j = 1; 38 | var k = 1; 39 | 40 | 41 | println("-----------------------------") ; 42 | println("Perform belief calculations "+N) ; 43 | println("-----------------------------") ; 44 | 45 | for (k <- 0 to N-1) { 46 | for (i <- 0 to dim-1) { 47 | x2(i) = 0; 48 | for (j <- 0 to dim-1) { 49 | x2(i) = x2(i) + A(i)(j)*scala.math.exp(x(j)); 50 | } 51 | } 52 | 53 | for (i <- 0 to dim-1) { 54 | x(i) = scala.math.log(x2(i)); 55 | } 56 | 57 | mysum = 0; 58 | for (i <- 0 to dim-1) { 59 | mysum = mysum + scala.math.exp(x(i)); 60 | } 61 | 62 | mynorm = scala.math.log(mysum); 63 | for (i <- 0 to dim-1) { 64 | x(i) = x(i) - mynorm; 65 | } 66 | 67 | 68 | } 69 | var stopTime = System.currentTimeMillis 70 | 71 | println("Elapsed time (s): " + (stopTime-startTime)/1000.0) 72 | println("Done with belief computations") 73 | println("-------------------------------") 74 | } 75 | } 76 | 77 | -------------------------------------------------------------------------------- /Scala/DoCopyMatrix.scala: -------------------------------------------------------------------------------- 1 | import Array._ 2 | 3 | object DoCopyMatrix { 4 | def main(args: Array[String]): Unit = { 5 | 6 | if (args.length == 0) { 7 | println("Need to provide matrix dimension") 8 | } 9 | 10 | //val n = 5000; 11 | //val n = 7000; 12 | // val n = 9000; 13 | val n = args(0).toInt; 14 | 15 | var elapsedTime: Long = 0 16 | 17 | val r = scala.util.Random; 18 | 19 | // Array declarations 20 | //------------------- 21 | var A = Array.ofDim[Float](n,n,3); 22 | 23 | var sum : Float = 0; 24 | 25 | var i = 1; 26 | var j = 1; 27 | var k = 1; 28 | 29 | // build a matrix 30 | for (i <- 0 to n-1) { 31 | for ( j <- 0 to n-1) { 32 | for ( k <- 0 to 2) { 33 | A(i)(j)(k) = r.nextFloat; 34 | } 35 | } 36 | } 37 | 38 | println("-----------------------------") ; 39 | println("Perform Matrix Copy: "+n) ; 40 | println("-----------------------------") ; 41 | 42 | var startTime = System.currentTimeMillis 43 | 44 | for (i <- 0 to n-1) { 45 | for ( j <- 0 to n-1) { 46 | A(i)(j)(0) = A(i)(j)(1); 47 | A(i)(j)(2) = A(i)(j)(0); 48 | A(i)(j)(1) = A(i)(j)(2); 49 | } 50 | } 51 | 52 | var stopTime = System.currentTimeMillis 53 | 54 | println("Elapsed time (s): " + (stopTime-startTime)/1000.0) 55 | println("-------------------------------") 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /Scala/DoCountUniqueWords.scala: -------------------------------------------------------------------------------- 1 | import scala.collection.mutable.HashSet 2 | import scala.io.Source 3 | 4 | object DoCountUniqueWords { 5 | def main(args: Array[String]): Unit = { 6 | 7 | if (args.length == 0) { 8 | println("Need to provide a file name.") 9 | } 10 | 11 | var uniqueWords = HashSet.empty[String] 12 | var words = Array.empty[String]; 13 | 14 | val filename = args(0); 15 | 16 | println("-----------------------------") ; 17 | println("Count the uniques words in: "+filename) ; 18 | println("-----------------------------") ; 19 | 20 | var startTime = System.currentTimeMillis; 21 | 22 | val bufferedSource = Source.fromFile(filename); 23 | 24 | for (line <- bufferedSource.getLines) { 25 | words = line.split(" ") 26 | for (i <- 0 to words.length - 1) { 27 | uniqueWords.add(words(i).replaceAll("[^a-zA-Z]", "").toLowerCase()) 28 | } 29 | } 30 | bufferedSource.close 31 | 32 | println(" Number of unique words: " + uniqueWords.size) 33 | 34 | var stopTime = System.currentTimeMillis 35 | println(" Elapsed time (s): " + (stopTime-startTime)/1000.0) 36 | 37 | } 38 | } 39 | 40 | -------------------------------------------------------------------------------- /Scala/DoEvaluateFunctions.scala: -------------------------------------------------------------------------------- 1 | import Array._ 2 | import scala.math._ 3 | 4 | object DoEvaluateFunctions { 5 | def main(args: Array[String]): Unit = { 6 | 7 | if (args.length == 0) { 8 | println("Need to provide the number of points") 9 | } 10 | 11 | val num_iterations = 10000; 12 | val n = args(0).toInt; 13 | 14 | var elapsedTime: Long = 0 15 | 16 | println("-----------------------------") ; 17 | println("Evaluate Functions: "+n) ; 18 | println("-----------------------------") ; 19 | 20 | var startTime = System.currentTimeMillis 21 | 22 | val a_min = -1500.0; 23 | val a_max = -1500.0; 24 | val h = (a_max - a_min)/(n-1); 25 | 26 | // Array declarations 27 | //------------------- 28 | var x = Array.ofDim[Double](n); 29 | var y = Array.ofDim[Double](n); 30 | 31 | var i = 1; 32 | var j = 1; 33 | 34 | // build a matrix 35 | for (i <- 0 to n-1) { 36 | x(i) = a_min + i*h; 37 | } 38 | 39 | for (i <- 0 to num_iterations-1) { 40 | for ( j <- 0 to n-1) { 41 | y(j) = sin(x(j)); 42 | x(j) = asin(y(j)); 43 | y(j) = cos(x(j)); 44 | x(j) = acos(y(j)); 45 | y(j) = tan(x(j)); 46 | x(j) = atan(y(j)); 47 | } 48 | } 49 | 50 | var stopTime = System.currentTimeMillis 51 | 52 | println("Elapsed time (s): " + (stopTime-startTime)/1000.0) 53 | println("-------------------------------") 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /Scala/DoFibonacci.scala: -------------------------------------------------------------------------------- 1 | 2 | object DoFibonacci { 3 | def main(args: Array[String]): Unit = { 4 | 5 | if (args.length == 0) { 6 | println("Need to provide an integer.") 7 | } 8 | val n = args(0).toInt; 9 | 10 | /* 11 | http://rosettacode.org/wiki/Fibonacci_sequence#Scala 12 | */ 13 | 14 | // Recursive 15 | 16 | def fibR(i:Int):Int = i match{ 17 | case 0 => 0 18 | case 1 => 1 19 | case _ => fibR(i-1) + fibR(i-2) 20 | } 21 | 22 | def fibI( n : Int ) : Int = { 23 | var a = 0 24 | var b = 1 25 | var i = 0 26 | 27 | while( i < n ) { 28 | val c = a + b 29 | a = b 30 | b = c 31 | i = i + 1 32 | } 33 | return a 34 | } 35 | 36 | println("-----------------------------") ; 37 | println("Iterative Fibonacci: "+n) ; 38 | println("-----------------------------") ; 39 | 40 | var startTime = System.currentTimeMillis 41 | 42 | var m1 = fibI(n); 43 | 44 | var stopTime = System.currentTimeMillis 45 | println(" Elapsed time (s): " + (stopTime-startTime)/1000.0 + " " + m1) 46 | 47 | println("-----------------------------") ; 48 | println("Recursive Fibonacci: "+n) ; 49 | println("-----------------------------") ; 50 | 51 | startTime = System.currentTimeMillis 52 | 53 | var m2 = fibR(n); 54 | 55 | stopTime = System.currentTimeMillis 56 | println(" Elapsed time (s): " + (stopTime-startTime)/1000.0 + " " + m2) 57 | } 58 | } 59 | 60 | -------------------------------------------------------------------------------- /Scala/DoLookAndSay.scala: -------------------------------------------------------------------------------- 1 | 2 | object DoLookAndSay { 3 | def main(args: Array[String]): Unit = { 4 | 5 | if (args.length == 0) { 6 | println("Need to provide an integer.") 7 | } 8 | val n = args(0).toInt; 9 | 10 | def lookandsayseq(number : String) : String = { 11 | val result = StringBuilder.newBuilder; 12 | 13 | var repeat = number.charAt(0); 14 | val l = number.length; 15 | var newnumber = number.substring(1, l) + " "; 16 | var cnt = 1; 17 | 18 | for (actual <- newnumber.toArray) 19 | { 20 | if (actual != repeat) 21 | { 22 | result.append(cnt + "" + repeat); 23 | cnt= 1; 24 | repeat= actual; 25 | } 26 | else 27 | { 28 | cnt = cnt + 1; 29 | } 30 | } 31 | return result.toString(); 32 | } 33 | 34 | println("-----------------------------") ; 35 | println("Look and say sequence: "+n) ; 36 | println("-----------------------------") ; 37 | 38 | var startTime = System.currentTimeMillis 39 | 40 | var num = "1223334444"; 41 | 42 | var i = 2; 43 | for (i <- 2 to n) { 44 | num = lookandsayseq(num); 45 | } 46 | // println(num); 47 | 48 | var stopTime = System.currentTimeMillis 49 | println(" Elapsed time (s): " + (stopTime-startTime)/1000.0 ) 50 | 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Scala/DoMarkovChain.scala: -------------------------------------------------------------------------------- 1 | import Array._ 2 | import math._ 3 | 4 | object DoMarkovChain { 5 | def main(args: Array[String]): Unit = { 6 | 7 | if (args.length == 0) { 8 | println("Need to provide matrix dimension") 9 | } 10 | val N = args(0).toInt; 11 | 12 | // val N = 5000; 13 | 14 | var elapsedTime: Long = 0; 15 | 16 | val r = scala.util.Random; 17 | val s = scala.util.Random; 18 | 19 | // Array declarations 20 | //------------------- 21 | 22 | var x = ofDim[Double](2); 23 | var x2 = ofDim[Double](2); 24 | 25 | var p1 : Double = 0; 26 | var p2 : Double = 0; 27 | 28 | var i = 1; 29 | var j = 1; 30 | var k = 1; 31 | 32 | var startTime = System.currentTimeMillis 33 | 34 | println("-----------------------------") ; 35 | println("Perform Markov Chain calculations "+N) ; 36 | println("-----------------------------") ; 37 | 38 | x(0) = 0; 39 | x(1) = 0; 40 | 41 | p1 = scala.math.exp(scala.math.sin(5*x(0)) - x(0)*x(0) - x(1)*x(1)); 42 | for (k <- 0 to N-1) { 43 | x2(0) = x(0) + 0.01*s.nextGaussian; 44 | x2(1) = x(1) + 0.01*s.nextGaussian; 45 | 46 | p2 = scala.math.exp(scala.math.sin(5*x2(0)) - x2(0)*x2(0) - x2(1)*x2(1)); 47 | 48 | if (r.nextDouble < (p2/p1)) { 49 | x(0) = x2(0); 50 | x(1) = x2(1); 51 | p1 = p2; 52 | } 53 | 54 | } 55 | var stopTime = System.currentTimeMillis 56 | 57 | println("Elapsed time (s): " + (stopTime-startTime)/1000.0) 58 | println("Done with Markov Chain computations") 59 | println("-------------------------------") 60 | } 61 | } 62 | 63 | -------------------------------------------------------------------------------- /Scala/DoMatrixMultiplication.scala: -------------------------------------------------------------------------------- 1 | import Array._ 2 | 3 | object DoMatrixMultiplication { 4 | def main(args: Array[String]): Unit = { 5 | 6 | object Matrix{ 7 | def apply( rowCount:Int, colCount:Int )( f:(Int,Int) => Float ) = ( 8 | for(i <- 1 to rowCount) yield 9 | ( for( j <- 1 to colCount) yield f(i,j) ).toList 10 | ).toList 11 | } 12 | 13 | if (args.length == 0) { 14 | println("Need to provide matrix dimension") 15 | } 16 | val dim1 = args(0).toInt; 17 | val dim2 = dim1 18 | val dim3 = dim1 19 | 20 | // val dim1 = 2000; 21 | // val dim2 = 2000; 22 | // val dim3 = 2000; 23 | 24 | var elapsedTime: Long = 0 25 | 26 | val r = scala.util.Random; 27 | 28 | // Array declarations 29 | //------------------- 30 | 31 | var A = ofDim[Float](dim1,dim2); 32 | var B = ofDim[Float](dim2,dim3); 33 | var C = ofDim[Float](dim1,dim3); 34 | 35 | var sum : Float = 0; 36 | 37 | var i = 1; 38 | var j = 1; 39 | var k = 1; 40 | 41 | // build a matrix 42 | for (i <- 0 to dim1-1) { 43 | for ( 0 <- 1 to dim2-1) { 44 | A(i)(j) = r.nextFloat; 45 | } 46 | } 47 | 48 | for (i <- 0 to dim2-1) { 49 | for ( j <- 0 to dim3-1) { 50 | B(i)(j) = r.nextFloat; 51 | } 52 | } 53 | 54 | 55 | println("-----------------------------") ; 56 | println("Perform Matrix Multiplication "+dim1) ; 57 | println("-----------------------------") ; 58 | 59 | 60 | // Perform the matrix multiplcation 61 | //--------------------------------- 62 | 63 | var startTime = System.currentTimeMillis 64 | 65 | for (i <- 0 to dim1-1) { 66 | for (j <- 0 to dim3-1) { 67 | for (k <- 0 to dim2-1) { 68 | sum = sum + A(i)(k)*B(k)(j); 69 | } 70 | C(i)(j) = sum; 71 | sum = 0; 72 | } 73 | } 74 | var stopTime = System.currentTimeMillis 75 | 76 | println("Elapsed time (s): " + (stopTime-startTime)/1000.0) 77 | println("Done with Matrix Multiplication") 78 | println("-------------------------------") 79 | } 80 | } 81 | 82 | -------------------------------------------------------------------------------- /Scala/DoMatrixMultiplicationJama.scala: -------------------------------------------------------------------------------- 1 | // Import library 2 | import Jama._ 3 | 4 | object DoMatrixMultiplicationJama { 5 | def main(args: Array[String]): Unit = { 6 | 7 | if (args.length == 0) { 8 | println("Need to provide matrix dimension") 9 | } 10 | val N = args(0).toInt; 11 | 12 | // val N = 2000 13 | 14 | // Create the matrix 15 | val A = new Matrix(N, N) 16 | val B = new Matrix(N, N) 17 | 18 | // Fill the matrix with random numbers 19 | val r = new scala.util.Random(0) 20 | 21 | for(i <- 0 until A.getRowDimension()) 22 | for(j <- 0 until A.getColumnDimension()) 23 | A.set(i, j, r.nextDouble()) 24 | 25 | for(i <- 0 until B.getRowDimension()) 26 | for(j <- 0 until B.getColumnDimension()) 27 | B.set(i, j, r.nextDouble()) 28 | 29 | println("---------------------------------------") ; 30 | println("JAMA-Perform Matrix Multiplication: "+N) ; 31 | println("---------------------------------------") ; 32 | 33 | var startTime = System.currentTimeMillis 34 | 35 | // Matrix product C=A'B 36 | // val C = A.transpose().times(B) 37 | val C = A.times(B) 38 | 39 | var stopTime = System.currentTimeMillis 40 | 41 | println("Elapsed time (s): " + (stopTime-startTime)/1000.0) 42 | println("---------------------------------------") ; 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Scala/DoMatrixMultiplicationLa4j.scala: -------------------------------------------------------------------------------- 1 | // Import library 2 | 3 | import org.la4j.matrix._ 4 | import org.la4j.linear._ 5 | 6 | object DoMatrixMultiplicationLa4j { 7 | def main(args: Array[String]): Unit = { 8 | 9 | if (args.length == 0) { 10 | println("Need to provide matrix dimension") 11 | } 12 | val N = args(0).toInt; 13 | 14 | // val N = 1500 15 | 16 | // Create the matrix 17 | val A = DenseMatrix.zero(N, N) 18 | val B = DenseMatrix.zero(N, N) 19 | 20 | // Fill the matrix with random numbers 21 | val r = new scala.util.Random(0) 22 | 23 | for(i <- 0 until A.rows()) 24 | for(j <- 0 until A.columns()) 25 | A.set(i, j, r.nextDouble()) 26 | 27 | for(i <- 0 until B.rows()) 28 | for(j <- 0 until B.columns()) 29 | B.set(i, j, r.nextDouble()) 30 | 31 | println("-----------------------------") ; 32 | println("Perform Matrix Multiplication: "+N) ; 33 | println("-----------------------------") ; 34 | 35 | var startTime = System.currentTimeMillis 36 | 37 | // Matrix product C=A'B 38 | // val C = A.transpose().multiply(B) 39 | val C = A.transpose().multiply(B) 40 | 41 | var stopTime = System.currentTimeMillis 42 | 43 | println("Elapsed time (s): " + (stopTime-startTime)/1000.0) 44 | println("-----------------------------") ; 45 | } 46 | } 47 | 48 | -------------------------------------------------------------------------------- /Scala/DoMunchausenNumber.scala: -------------------------------------------------------------------------------- 1 | 2 | import Array._ 3 | import scala.math.pow 4 | 5 | object DoMunchausenNumber { 6 | def main(args: Array[String]): Unit = { 7 | 8 | def raisedto(n:Int): Double = { 9 | if (n == 0) { 10 | return 0 11 | } 12 | else { 13 | return pow(n,n) 14 | } 15 | } 16 | 17 | println("-----------------------------") ; 18 | println("Looking for the Munchausen Numbers") ; 19 | println("-----------------------------") ; 20 | 21 | var startTime = System.currentTimeMillis 22 | 23 | var power_of_digits = Array.ofDim[Double](10) 24 | for (k <- 0 to 9) { 25 | power_of_digits(k) = raisedto(k) 26 | } 27 | 28 | var i = 0 29 | var n = 0 30 | 31 | while (n < 4) { 32 | if (i == (i.toString.toCharArray.map(d => power_of_digits(d.asDigit))).sum) { 33 | n = n + 1 34 | println(s"Munchausen Number $n: $i ") 35 | } 36 | i = i + 1 37 | } 38 | 39 | var stopTime = System.currentTimeMillis 40 | println(" Munchausen Elapsed time (s): " + (stopTime-startTime)/1000.0 ) 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-slate -------------------------------------------------------------------------------- /docs/2017edition.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/docs/2017edition.pdf -------------------------------------------------------------------------------- /docs/2018edition.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/docs/2018edition.pdf -------------------------------------------------------------------------------- /docs/2019edition.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JulesKouatchou/basic_language_comparison/ae5263646ed588e890379f1e8073c4f7dc65aeac/docs/2019edition.pdf --------------------------------------------------------------------------------