KAZ999
KAZ999

Reputation: 1

Fortran prompting user and reading polynomial input

I am writing a program to calculate the roots of a polynomial. The user is prompted a polynomial of no greater than fourth order (not a file read). How do I read a polynomial input in Fortran? I thought about using 1D array, each index representing the degree and the number representing the coefficient, but what about the plus and minus signs? I don't want to restrict the user to a polynomial with one mathematical operation.

Upvotes: 0

Views: 200

Answers (1)

IPribec
IPribec

Reputation: 236

If you don't care about pretty printing the polynomial without brackets it's not that difficult:

program prompt_read

implicit none
integer, parameter :: wp = kind(1.0d0)    ! work precision

!> Polynomial coefficients (maximum degree = 4), only real values allowed
real(wp) :: a(0:4)
!> Polynomial degree
integer :: n

! initialize coefficients to zero
a = 0

write(*,'(A)',advance='no') "Enter polynomial degree (1-4): "
read(*,*) n

! handle erroneous input
if (n > 4 .or. n < 1) then
   write(*,'(A)') 'Input error. Try again.'
   stop
end if

write(*,'(A)',advance='no') "Enter polynomial coefficients (ascending powers of x): "
read(*,*) a(0:n)

write(*,'(A)') "The polynomial received was " // polystr(a(0:n))

! ... continue with calculation of roots

contains

   pure function polystr(coeffs)
      real(wp), intent(in) :: coeffs(0:)
      character(len=:), allocatable :: polystr
      character(32) :: s
      integer :: i 

      write(s,'("(",F0.3,")")') coeffs(0)
      polystr = trim(s)

      do i = 1, ubound(coeffs,1)
         write(s,'("(",F0.3,")")') coeffs(i)
         if (i == 1) then
            s = trim(s) // '*x'
         else if (i > 1) then
            s = trim(s) // '*x^' // achar(iachar('0') + i)
         end if
         polystr = polystr // ' + ' // trim(s) 
      end do
   end function

end program

Example output:

$ gfortran -Wall -o prompt_read prompt_read.f90 
$ ./prompt_read
Enter polynomial degree (1-4): 3
Enter polynomial coefficients (ascending powers): 1,-2,3.,-4.2
The polynomial entered is (1.000) + (-2.000)*x + (3.000)*x^2 + (-4.200)*x^3

A few notes/ideas:

  • use a custom lower bound of 0 to make the array index match the power of the monomial
  • you can read both space- or comma-delimited input
  • the polystr function can only handle polynomials up to degree 9
  • have a look at polyroots-fortran, a collection of existing polynomial root solvers in Fortran
  • put the body of the program in an "infinite" do-end do loop with a suitable exit condition (for example upon pressing the key q); add a brief help message to explain usage of the program

Upvotes: 1

Related Questions