↜ Back to index Introduction to Numerical Analysis 2
Solutions for Part b–Lecture 1
Exercise 2
implicit none
print *, maximum(1., 2.)
print *, maximum(1., 1.)
print *, maximum(1., -1.)
print *, positive_part(1.)
print *, positive_part(-2.)
contains
function maximum(x, y)
real x, y, maximum
if (x > y) then
= x
maximum else
= y
maximum end if
end
function positive_part(x)
real x, positive_part
= maximum(x, 0.)
positive_part end
end
Exercise 3
implicit none
real a(3), b(3)
= [3.0, 2.5, 5.0]
a = [1.0, -3.0, 2.0]
b
print *, inner(a, b)
contains
function inner(x, y)
real x(:), y(:), inner
integer i
if (size(x) /= size(y)) then
stop 'arrays x and y must have the same size'
end if
= 0
inner do i = 1, size(x)
= inner + x(i) * y(i)
inner end do
end
end
Exercise 4
implicit none
real a(3,2), x(2)
1, :) = [1., -1.]
a(2, :) = [2., 3.]
a(3, :) = [6., 7.]
a(
= [3., -1.]
x
print *, mv_mul(a, x)
contains
function mv_mul(a, x)
real a(:,:), x(:), mv_mul(size(a, 1))
integer i, j
if (size(a, 2) /= size(x)) then
stop 'the number of colums of a and size x are different'
end if
do i = 1, size(a, 1)
= inner(a(i, :), x)
mv_mul(i) end do
end
function inner(x, y)
real x(:), y(:), inner
integer i
if (size(x) /= size(y)) then
stop 'arrays x and y must have the same size'
end if
= 0
inner do i = 1, size(x)
= inner + x(i) * y(i)
inner end do
end
end
Exercise 5
We reuse function inner
from Exercise 4.
implicit none
real x(3)
= [1., 2., -3.]
x
print *, norm(x)
contains
function norm(x)
real x(:), norm
= sqrt(inner(x, x))
norm end
function inner(x, y)
real x(:), y(:), inner
integer i
if (size(x) /= size(y)) then
stop 'arrays x and y must have the same size'
end if
= 0
inner do i = 1, size(x)
= inner + x(i) * y(i)
inner end do
end
end