↜ Back to index Introduction to Numerical Analysis 1
Solution Lecture a7
Exercise 1
! Implementation of Newton's method for exp x + x = 5
! with a stopping condition
implicit none
real x, F, Fprime, d, p, q
integer k
! Enter the starting x0
read *, x
do k = 1, 100
F = exp(x) + x - 5
Fprime = exp(x) + 1
d = F / Fprime
x = x - d
if (abs(d) < 1e-3) then
print *, k, 'iterations needed'
exit
endif
enddo
endIterations needed: 5, 8, 12
Exercise 2
! Implementation of Newton's method for x^3 + p x + q = 0
! with a stopping condition
implicit none
real x, F, Fprime, d, p, q
integer k
read *, p, q, x
print *, x
do k = 1, 100
F = x**3 + p * x + q
Fprime = 3 * x**2 + p
if (abs(Fprime) < 1e-6) then
print *, 'Error: the derivative is too close to zero'
stop
endif
d = F / Fprime
x = x - d
! We stop the iteration if x does not change more than a certain value
if (abs(d) < 1e-3) then
print *, 'x =', x
print *, k, 'iterations needed'
! stop the loop
stop
endif
print *, x
enddo
print *, 'Method does not converge'
endExercise 3
! Implementation of Newton's method for x^3 + p x + q = 0
! with a stopping condition
implicit none
real x, F, Fprime, d, p, q
integer k, i, r
read *, r
do i = -r, r
x = i
p = -2.
q = 2.
do k = 1, 100
F = x**3 + p * x + q
Fprime = 3 * x**2 + p
if (abs(Fprime) < 1e-6) then
print *, 'Error: the derivative is too close to zero'
stop
endif
d = F / Fprime
x = x - d
! We stop the iteration if x does not change more than a certain value
if (abs(d) < 1e-3) then
print *, i, k
! stop the loop
exit
endif
enddo
enddo
end