↜ 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
            maximum = x
        else
            maximum = y
        end if
    end

    function positive_part(x)
        real x, positive_part

        positive_part = maximum(x, 0.)
    end
end

Exercise 3

implicit none
real a(3), b(3)

a = [3.0, 2.5, 5.0]
b = [1.0, -3.0, 2.0]

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

        inner = 0
        do i = 1, size(x)
            inner = inner + x(i) * y(i)
        end do  
    end
end

Exercise 4

implicit none
real a(3,2), x(2)

a(1, :) = [1., -1.]
a(2, :) = [2., 3.]
a(3, :) = [6., 7.]

x = [3., -1.]

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)
            mv_mul(i) = inner(a(i, :), x)
        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

        inner = 0
        do i = 1, size(x)
            inner = inner + x(i) * y(i)
        end do  
    end
end

Exercise 5

We reuse function inner from Exercise 4.

implicit none
real x(3)

x = [1., 2., -3.]

print *, norm(x)

contains
    function norm(x) 
        real x(:), norm

        norm = sqrt(inner(x, x))
    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

        inner = 0
        do i = 1, size(x)
            inner = inner + x(i) * y(i)
        end do  
    end

end