Page 1 of 1

Language: Fortran 90 Question: - How do I fix my code for Newton's method in Fortran 90 to print the correct values, and

Posted: Sun May 15, 2022 12:22 pm
by answerhappygod
Language: Fortran 90
Question:
- How do I fix my code for Newton's method in Fortran 90 to
print the correct values, and is there any way to improve my
code?
Goal:
- Solve newton's method from x = 0 to x = 2.8 in steps of
0.1.
- create a 2D array storing x values (column 1) and # of
iterations until root is found for each x value (column 2).
My issue:
- The second column in the array is not printing the
correct values (from x = 0.5 to x= 2.89).
Below is my Fortran code:
Language Fortran 90 Question How Do I Fix My Code For Newton S Method In Fortran 90 To Print The Correct Values And 1
Language Fortran 90 Question How Do I Fix My Code For Newton S Method In Fortran 90 To Print The Correct Values And 1 (38.2 KiB) Viewed 60 times
My output (which goes wrong around x= 0.5 or x= 0.6):
Language Fortran 90 Question How Do I Fix My Code For Newton S Method In Fortran 90 To Print The Correct Values And 2
Language Fortran 90 Question How Do I Fix My Code For Newton S Method In Fortran 90 To Print The Correct Values And 2 (39.47 KiB) Viewed 60 times
module newtonsMethod implicit none real, parameter :: Epsilon = 0.0001 real, parameter :: Max_Itns 100 contains !function real function f(x) real :: X f = x**3 end function I derivative of function real function p(x) real :: x p = 3*x**2 end function ! approdximation of root real function X_new(x) real :: x X_new = x - (f(x) / p(x)) end function ! returns # of iterations til root is found integer function convergence(x) integer :: i = 1 real :: x1, x, diff, xo x = x do while(i < Max_Itns) x1 = X_new(x) diff abs(x1 - x) if(p(x) e) then convergence = 100 EXIT else if (diff <= Epsilon) then convergence = i EXIT else X = x1 i = i + 1 end if end do X = x end function end module

program newtonsMethod_array use newtonsMethod implicit none real, dimension (2,30) :: myArray call store_Xandc_values (myArray) contains subroutine store_Xandc_values (A) real :: X, step, c, i, j, div real, dimension (2,30) :: A X - @ step = 0.1 div = 2 = do j = 1, 30 do i = 1, 2 if(mod(i, div) /= ) then Ali,j) - x convergence (x) X = X + step else Ali,j) = 0 end if end do end do do j-1, 30 print *, (A[i,j), i = 1,2) end do end subroutine end program

0.0000000E+00 0.1000000 0.2000000 0.3000000 0.4000000 0.5000000 0.6000000 0.7000000 0.8000001 0.9000001 1.000000 1.100000 1.200000 1.300000 1.400000 1.500000 1.600000 1.700000 1.800000 1.900000 2.000000 2.100000 2.200000 2.300000 2.400000 2.500000 2.600000 2.700000 2.799999 2.899999 100.0000 16.00000 33.00000 51.00000 69.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000 88.00000