this is meant so that it runs the loop until pi2 - pi is in a certain tolerance, variable tol. For some reason it doesnt seem right but I don't know of any other way to run a loop until the difference of two numbers falls within a certain range.
What I don't understand is even if I remove the delete the cout statements from the loop, it still outputs 0 even though there is no ouptput statement. What is causing this?
Last edited by mattyharge on Thu 02-24-2005 6:48PM, edited 1 time in total.
I'm not in that CS 78 , but I helped somebody earlier with that assignment. For starters, you don't need that 1 in 4*(1-((pow.....stuff). If you evaluate (-1)^n / (2*n+1) at n=0 it gives you 1. The 1 is part of the approximation series.
As to why it's zero:
First time through loop:
pi = 1-(-1)^0 = 0. Anything to the zero is 1. So you have 1-1 for the numerator. 0/1 = 0; First part of your loop yields pi = 0
pi2 = 1-(-1) = 2 for numerator, 3 for denomiator, pi2=2/3
Since you #include<cmath> you can use the absolute value function. Makes the condtional statement of the do-while a little easier to read.
while(abs((pi2-pi)) >= tolerance) .........2/3-0
check conditional , 2/3 > tol, repeat loop again
2nd Time through loop:
now r=1 , n=2
pi = 0+2/3=2/3
pi2-pi = 2/3-2/3 = 0 ......This is why you're getting zeros for your answer. You keep this pattern up, you add a value, and immediately subtract it which will always give zero.
It's an infinite loop because of your conditional statement. Read it carefully. If pi2-pi > tol, repeat. OR if pi2-pi < tol, repeat. OR if pi2-pi = tol, repeat. Well, no matter what pi2-pi gives, you'll always repeat because pi2-pi will always evaluate to being greater than tol, less than tol, or equal to tol. What you meant to say was
do{
//stuff
}while(fabs(pi2-pi) >= tol);
Hope this helps clear things up some.
Last edited by tansir1 on Fri 02-25-2005 10:55AM, edited 1 time in total.
It's been a while since I've used abs, labs, and fabs, but make sure you use the right one. labs is for longs, fabs is for floats, but I don't remember if abs is just for ints or not.
Users browsing this forum: No registered users and 2 guests
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum