hopfinvariant7455
hopfinvariant7455

Reputation: 21

Problems with do while implementation

I am having problems with a do while implementation for a sine taylor series. Editing the do loop to do bb = 1, 10 , 2 gives an expected result well within the margin of error, however when running the desired implementation of the do loop (do while(abs(sineseries) - accuracy > 0), will always give an answer equal to 1. So I have narrowed the possibilities down to the do while loop implementation being faulty.

program taylor
 implicit none
 real :: x
 real :: sineseries, nfactsine
 real, parameter :: accuracy = 1.e-10
 integer :: signum, bb

 nfactsine = 1
 signum = 1
 write(*,*) "Write your input value"
 read(*,*) x
 sineseries = 0

  do while(abs(sineseries) - accuracy > 0)
    sineseries = sineseries + (signum*x**bb)/nfactsine
    nfactsine = nfactsine*(bb+1)*(bb+2)
    signum = -signum

  end do
  write(*,*) sineseries, sin(x)
end program taylor

Upvotes: 2

Views: 69

Answers (1)

francescalus
francescalus

Reputation: 32366

The two types of loops are not doing the same thing.

In the loop

do bb=1, 10, 2
  ...
end do

you have loop control with variable bb. This variable takes the values 1, 3, ..., 9 at iterations as the loop proceeds.

The do while does not have this control: you must replicate the increment of bb manually:

bb=1
do while (...)
  ...
  bb=bb+2
end do

As Pierre de Buyl commented, you also have an error in the termination condition for the indefinite iteration count. The condition initially evaluates as false, so the loop body isn't executed even once.

Upvotes: 1

Related Questions