Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

I can't find the mistake 1

Status
Not open for further replies.

atilarceus

Programmer
Apr 15, 2016
2
BR
Hey guys, i were writing a code to calculate the digits of pi using the leibniz formula; the code is shown below:
Code:
program picalc
    implicit none
    real :: pi,g
    integer :: i,l
    pi=0
    print *, "Tell me the precision you want"
    read(*,*) l
    do i=0,l
        g = (1/(4*i+1))-(1/(4*i+3))
        pi=pi+g
    end do

   print *, 'The calculated value of pi is', 4*pi
end program picalc
The thing is, the code can be compiled, but the 'g' expression inside the loop gives 1 in the first iteration, when it should be 0,6666666..., and zero in every other iteration (what clearly is wrong), not giving the value of pi. I want to know what i'm doing wrong and how can i fix it. Thanks guys!
Obs.:forgive my english, i dunno if i wrote something wrong, i really didn't check it in a translator.
 
As you already know, when programming computers, there is a difference on how integers are handle and how reals are handled...that is why you declare some variable one way and others a different way.

When dealing with integers, also known as integral numbers, the division is called "integral division". With integers, this operation yields only the whole number of the result and throws away fractions. Examples:

1/4 = 0
2/4 = 0
5/4 = 1
7/4 = 1
9/4 = 2

When dealing with reals, the result is what most (non-programming) people expect:

1.0/4.0 = 0.25
2.0/4.0 = 0.5

So, in your program above, just add decimal points to the numbers in the equation for g.

 
Thank you so much salgerman, i really appreciate the help and the patience :D
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top