ユーマちゃんのブログ

質問・要望はTwitterもしくはコメントで。返信はTwitterで。

Programming Example

program repo
implicit none
real(8)::up,xold=0.0,xnew !Up is border. Other two are terms of series.
character(16)::e !This e will be used to say conclusion correctly.
integer::i=0 !counter

print*,"Assign the numerical tolerance (e.g. 1D-6)"
read*,up !Read up here.
print*,"Input the guessed value"
read*,xnew !Read x_1 here.

write (e,'(f0.15)') up
!1d-6 can't be shown correctly if you "print up".
!So I changed it to character here.

do while (abs(xnew-xold)>=up) !This shows this loop will stop when xn converges enough.
xold = xnew !substitue xnew provided before this step for xold.
xnew = xnew - res(xnew)/dres(xnew,up) !The xnew provided before this step is changed into "new" xnew.
i = i + 1 !Add counter by 1.
print*,"Iteration =",i,"Convergent result =",xnew,"Residual =",res(xold)
end do
!This is conclusion.
print*,"The numerical solution with the precision up to",e,"is",xnew

contains
!These functions below are ones used above.
function res(x)
real(8) res, x
res = x**2.0 - 2.0**x
end function

function dres(x,up)
real(8) dres,x,up
dres = (res(x+up)-res(x))/up
end function

end program repo