fortran - Do sum with alternating sign in argument -


i'm doing numerical exercises in fortran 90. when trying sum alternating sign in argument noticed (in manner did it) fortran don't know how that.

for example want sum on k 1 10 of ((-1)^k)/2k did was

sumk = 0 k = 1,10    sumk = ((-1)**k)/(2*k) + sumk end 

but output sumk = 1. did wrong?

if k integer, performing integer operations. these might not expect, e.g. 1/2 = 0. using floats result in 0.5, of course, conversion integers result in 0.

so, basically, part add sumk 0 in case, leading sumk=0 in end. prevent this, need take quotient floats:

  sumk = real(((-1)**k))/real(2*k) + sumk 

then, result -0.322817445 (which verified using wolfram alpha).


of course, there several ways improve this, such computing (-1)**k iteratively, or replacing modulo operation.


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -