ParaMonte Fortran 2.0.0 Parallel Monte Carlo and Machine Learning LibrarySee the latest version documentation.
pm_mathSqrt Module Reference

This module contains procedures and generic interfaces and generic interfaces for computing the square root of integers. More...

## Data Types

interface  getSqrt
Generate and return the integer square root of an input non-negative integer. More...

## Variables

character(*, SK), parameter MODULE_NAME = "@pm_mathSqrt"

## Detailed Description

This module contains procedures and generic interfaces and generic interfaces for computing the square root of integers.

In number theory, the integer square root (getSqrt) of a non-negative integer $$n$$ is the non-negative integer $$m$$ which is the greatest integer less than or equal to the square root of $$n$$,

$$\mbox{getSqrt}(n) = \lfloor{\sqrt{n}}\rfloor ~.$$

For example,

$$\mbox{getSqrt}(27) = \lfloor{\sqrt{27}}\rfloor = \lfloor 5.19615242270663\ldots \rfloor = 5 ~.$$

Two methods of finding the integer square root include linear and binary search, both of which are implemented by the procedures of this module.

Note
While the procedures of this module return getSqrt(n), the greatest integer less than or equal to the square root of a given integer, one can readily compute the smallest integer a greater than or equal to the square root of n as a = 1 + getSqrt(n - 1).
This number is equivalent to the ceiling of the exact square root of n.
Benchmarks:

Benchmark :: The runtime performance of getSqrt for integer vs. real input ndim.

1! Test the performance of getSqrt() with and without the selection control argument.
2program benchmark
3
4 use pm_bench, only: bench_type
7 use pm_kind, only: IK, LK, IKG => IK, RK, SK
8 use iso_fortran_env, only: error_unit
9
10 implicit none
11
12 integer(IK) :: ibench
13 integer(IK) :: iposint
14 integer(IK) :: fileUnit
15 integer(IKG) :: intSqrt, dumm
16 integer(IKG) , allocatable :: posint(:)
17 type(bench_type) , allocatable :: bench(:)
18
19 bench = [ bench_type(name = SK_"getSqrtBinary", exec = getSqrtBinary, overhead = setOverhead) &
20 , bench_type(name = SK_"getSqrtLinear", exec = getSqrtLinear, overhead = setOverhead) &
21 , bench_type(name = SK_"floor_sqrt", exec = floor_sqrt, overhead = setOverhead) &
22 ]
23
24 write(*,"(*(g0,:,' '))")
25 write(*,"(*(g0,:,' vs. '))") (bench(ibench)%name, ibench = 1, size(bench))
26 write(*,"(*(g0,:,' '))")
27
28 open(newunit = fileUnit, file = "main.out", status = "replace")
29
30 write(fileUnit, "(*(g0,:,','))") "Integer", (bench(ibench)%name, ibench = 1, size(bench))
31 posint = getUnique(int(getLogSpace(0._RK, log(real(huge(0_IK), RK)), count = 50_IK), IKG))
32 loopOverArraySize: do iposint = 1, size(posint)
33
34 write(*,"(*(g0,:,' '))") "Benchmarking with posint = ", posint(iposint)
35 do ibench = 1, size(bench)
36 bench(ibench)%timing = bench(ibench)%getTiming(minsec = 0.04_RK)
37 end do
38 write(fileUnit,"(*(g0,:,','))") posint(iposint), (bench(ibench)%timing%mean, ibench = 1, size(bench))
39
40 end do loopOverArraySize
41 write(*,"(*(g0,:,' '))") dumm
42 write(*,"(*(g0,:,' '))")
43
44 close(fileUnit)
45
46contains
47
48 !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
49 ! procedure wrappers.
50 !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
51
53 call getDummy()
54 end subroutine
55
56 subroutine getDummy()
57 dumm = intSqrt - dumm
58 end subroutine
59
60 subroutine getSqrtBinary()
61 use pm_mathSqrt, only: getSqrt, binary
62 intSqrt = getSqrt(posint(iposint), binary)
63 call getDummy()
64 end subroutine
65
66 subroutine getSqrtLinear()
67 use pm_mathSqrt, only: getSqrt, linear
68 intSqrt = getSqrt(posint(iposint), linear)
69 call getDummy()
70 end subroutine
71
72 subroutine floor_sqrt()
73 intSqrt = floor(sqrt(real(posint(iposint), RK)), IKG)
74 call getDummy()
75 end subroutine
76
77end program benchmark
Generate count evenly-logarithmically-spaced points over the interval [base**logx1,...
Generate and return a vector of unique values in the input array.
Generate and return an object of type timing_type containing the benchmark timing information and sta...
Definition: pm_bench.F90:574
Generate and return the integer square root of an input non-negative integer.
This module contains procedures and generic interfaces for generating arrays with linear or logarithm...
This module contains procedures and generic interfaces for finding unique values of an input array of...
This module contains abstract interfaces and types that facilitate benchmarking of different procedur...
Definition: pm_bench.F90:41
This module defines the relevant Fortran kind type-parameters frequently used in the ParaMonte librar...
Definition: pm_kind.F90:268
integer, parameter RK
The default real kind in the ParaMonte library: real64 in Fortran, c_double in C-Fortran Interoperati...
Definition: pm_kind.F90:543
integer, parameter LK
The default logical kind in the ParaMonte library: kind(.true.) in Fortran, kind(....
Definition: pm_kind.F90:541
integer, parameter IK
The default integer kind in the ParaMonte library: int32 in Fortran, c_int32_t in C-Fortran Interoper...
Definition: pm_kind.F90:540
integer, parameter SK
The default character kind in the ParaMonte library: kind("a") in Fortran, c_char in C-Fortran Intero...
Definition: pm_kind.F90:539
This module contains procedures and generic interfaces and generic interfaces for computing the squar...
Definition: pm_mathSqrt.F90:67
This is the class for creating benchmark and performance-profiling objects.
Definition: pm_bench.F90:386
subroutine bench(sort, arraySize)

Example Unix compile command via Intel ifort compiler
1#!/usr/bin/env sh
2rm main.exe
3ifort -fpp -standard-semantics -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
4./main.exe

Example Windows Batch compile command via Intel ifort compiler
1del main.exe
2set PATH=..\..\..\lib;%PATH%
3ifort /fpp /standard-semantics /O3 /I:..\..\..\include main.F90 ..\..\..\lib\libparamonte*.lib /exe:main.exe
4main.exe

Example Unix / MinGW compile command via GNU gfortran compiler
1#!/usr/bin/env sh
2rm main.exe
3gfortran -cpp -ffree-line-length-none -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
4./main.exe

Postprocessing of the benchmark output
1#!/usr/bin/env python
2
3import matplotlib.pyplot as plt
4import pandas as pd
5import numpy as np
6
7import os
8dirname = os.path.basename(os.getcwd())
9
10fontsize = 14
11
12df = pd.read_csv("main.out", delimiter = ",")
13colnames = list(df.columns.values)
14
15
18
19ax = plt.figure(figsize = 1.25 * np.array([6.4,4.6]), dpi = 200)
20ax = plt.subplot()
21
22for colname in colnames[1:]:
23 plt.plot( df[colnames[0]].values
24 , df[colname].values
25 , linewidth = 2
26 )
27
28plt.xticks(fontsize = fontsize)
29plt.yticks(fontsize = fontsize)
30ax.set_xlabel(colnames[0], fontsize = fontsize)
31ax.set_ylabel("Runtime [ seconds ]", fontsize = fontsize)
32ax.set_title(" vs. ".join(colnames[1:])+"\nLower is better.", fontsize = fontsize)
33ax.set_xscale("log")
34ax.set_yscale("log")
35plt.minorticks_on()
36plt.grid(visible = True, which = "both", axis = "both", color = "0.85", linestyle = "-")
37ax.tick_params(axis = "y", which = "minor")
38ax.tick_params(axis = "x", which = "minor")
39ax.legend ( colnames[1:]
40 #, loc='center left'
41 #, bbox_to_anchor=(1, 0.5)
42 , fontsize = fontsize
43 )
44
45plt.tight_layout()
46plt.savefig("benchmark." + dirname + ".runtime.png")
47
48
51
52ax = plt.figure(figsize = 1.25 * np.array([6.4,4.6]), dpi = 200)
53ax = plt.subplot()
54
55for colname in colnames[1:]:
56 plt.plot( df[colnames[0]].values
57 , df[colname].values / df[colnames[1]].values
58 , linewidth = 2
59 )
60
61plt.xticks(fontsize = fontsize)
62plt.yticks(fontsize = fontsize)
63ax.set_xlabel(colnames[0], fontsize = fontsize)
64ax.set_ylabel("Runtime compared to {}".format(colnames[1]), fontsize = fontsize)
65ax.set_title("Runtime Ratio Comparison. Lower means faster.\nLower than 1 means faster than {}().".format(colnames[1]), fontsize = fontsize)
66ax.set_xscale("log")
67#ax.set_yscale("log")
68plt.minorticks_on()
69plt.grid(visible = True, which = "both", axis = "both", color = "0.85", linestyle = "-")
70ax.tick_params(axis = "y", which = "minor")
71ax.tick_params(axis = "x", which = "minor")
72ax.legend ( colnames[1:]
73 #, bbox_to_anchor = (1, 0.5)
74 #, loc = "center left"
75 , fontsize = fontsize
76 )
77
78plt.tight_layout()
79plt.savefig("benchmark." + dirname + ".runtime.ratio.png")

Visualization of the benchmark output

Benchmark moral
1. The benchmark procedures named getSqrtBinary and getSqrtLinear call the generic interface getSqrt with a method argument of type binary_type and linear_type respectively.
2. From the benchmark results it appears that the binary search algorithm for computing the integer square root is significantly faster than the linear search method.
The binary search algorithm is also faster than the naive approach based on the formula floor(sqrt(real(posint, RK))).
Test:
test_pm_mathSqrt

Final Remarks

If you believe this algorithm or its documentation can be improved, we appreciate your contribution and help to edit this page's documentation and source file on GitHub.

1. If you use any parts or concepts from this library to any extent, please acknowledge the usage by citing the relevant publications of the ParaMonte library.
2. If you regenerate any parts/ideas from this library in a programming environment other than those currently supported by this ParaMonte library (i.e., other than C, C++, Fortran, MATLAB, Python, R), please also ask the end users to cite this original ParaMonte library.

This software is available to the public under a highly permissive license.
Help us justify its continued development and maintenance by acknowledging its benefit to society, distributing it, and contributing to it.

Author:
Amir Shahmoradi, April 23, 2017, 1:36 AM, Institute for Computational Engineering and Sciences (ICES), University of Texas at Austin

## ◆ MODULE_NAME

 character(*, SK), parameter pm_mathSqrt::MODULE_NAME = "@pm_mathSqrt"

Definition at line 75 of file pm_mathSqrt.F90.