Saturday, 8 February 2025

ascii2spec.f90

Following up the last post, where I documented the function which maps the ASCII representation of the letters s, p, d, f, g, h, i, j, k, to the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,  I complete the job today where I mentioned that one reason to do this mapping is to allow translation between the letters and the numbers in a computer language in a mathematical way.

Before coding up the polynomial function which does the mapping, it is helpful / necessary to re-express it in a different form that is not so prone to rounding errors.  Such a thing can be done by writting the polynomial in Horner form, which results in 

 

Here, then is a Fortran code which uses this form of the polynomial, which it can evaluate without error (with the use of double precision intermediary values).  If you want to use it, you can use the module a2s.  A sample code showing that it works is included in the snippet below

! take the ascii value for a spectroscopic identifier (s, p, d, f etc)
! and return the corresponding l value (0, 1, 2, ) etc.

module a2s
  contains
  function ascii2spec(x)
    implicit none
    integer, parameter :: rk=selected_real_kind(16)
    integer :: ascii2spec
    integer :: x
    
    ascii2spec= NINT(4.726949979612458e10_rk + x*(-3.5777271221003e9_rk + & 
         x*(1.184502721723563e8_rk + x*(-2.2405263573528733e6_rk + &
         x*(26482.917002197904_rk + &
         x*(-200.30039731359176_rk + &
         x*(0.946665443609888_rk + &
         (-0.002556173250617695_rk + (47*x)/1.5567552e7_rk)*x)))))))
  end function ascii2spec
end module a2s

program a2s_test
  use a2s
  integer, parameter :: rk=selected_real_kind(16)
  integer :: x
  
  print *,"s",ascii2spec(iachar("s"))
  print *,"p",ascii2spec(iachar("p"))
  print *,"d",ascii2spec(iachar("d"))
  print *,"f",ascii2spec(iachar("f"))
  print *,"g",ascii2spec(iachar("g"))
  print *,"h",ascii2spec(iachar("h"))
  print *,"i",ascii2spec(iachar("i"))
  print *,"j",ascii2spec(iachar("j"))
  print *,"k",ascii2spec(iachar("k"))

end program a2s_test