fortran-lang / stdlib

Fortran Standard Library
https://stdlib.fortran-lang.org
MIT License
1.09k stars 167 forks source link

Proposal to add new functions to stdlib_math module #365

Open aman-godara opened 3 years ago

aman-godara commented 3 years ago

About: This issue concerns with proposing new functions to stdlib_math module.

I am working on building a new module sdlib_math for fortran. As the name suggests this module aims to provide general purpose mathematical functions. I wanted to know about some of the functions that people are requesting so that we can add them to this module. One of the proposed function was clip(Issue #319).

I propose to add some other functions like gcd, lcm, etc. to this library, if they don't already exist. So I decided to take review from the community regarding this. Please propose functions that you would like to have in stdlib_math module, so that fortran community can have discussions on them and start adding to the codebase.

Some resources: Numpy Math Matlab Discrete Math Python Math module Java Math

Beliavsky commented 3 years ago

Maybe a function to determine if an integer is prime and a subroutine for prime factorization?

milancurcic commented 3 years ago

This issue was mentioned in the Youtube video by Conor Hoekstra (@codereport) who compared 16 languages in an implementation of a simple problem (finding the gcd).

https://www.youtube.com/watch?v=UVUjnzpQKUo

Unfortunately, I think Fortran was the only language in the video that doesn't have gcd() either built into the language or standard library. We can easily improve this by implementing it in stdlib_math.

Here's a simple implementation using Euclid's method, adapted from (https://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/gcd.html):

  elemental integer function gcd(x, y)
    integer, intent(in) :: x, y
    integer :: a, b, c
    a = x
    b = y

    ! Swap a and b if a < b
    if (a < b) then 
      c = a
      a = b
      b = c
    end if

    ! Iterate until remainder is zero
    do
      c = mod(a, b)    
      if (c == 0) exit 
      a = b
      b = c
    end do

    gcd = b
  end function gcd

I think gcd() would be a good first issue for new contributors.

milancurcic commented 3 years ago

@FortranFan posted a similar implementation here: https://github.com/j3-fortran/fortran_proposals/issues/221#issuecomment-907638974.