GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 25-Nov-2005, 21:27
green lantern green lantern is offline
New Member
 
Join Date: Nov 2005
Posts: 5
green lantern is on a distinguished road
Angry

C++ exponent help please!!!!!


CPP / C++ / C Code:
//PI.cpp : Defines the entry point for 
//the console application.
//This program will approximate pi to n the number of decimal 
//spaces the user choses.  This program will display the result
//for the user to see.

//import packages
#include <cmath>
#include <stdio.h>
#include <cstdlib>
#include "stdafx.h"
#include <iostream>
using namespace std;

double n = 0;
double max_n = 0;
double pi = 0;


			
//start main program
int _tmain(int argc, _TCHAR* argv[])
{
    //declare and initialize variables
	char ans = 'y';
		

	//start loop
	do 
	{	
		//prompt user for the number of decimals to which 
		//approximate pi
		cout << "ENTER THE NUMBER OF DECIMALS TO WHICH APPROXIMATE PI ";
		cin >> max_n;
		
		while (n <= max_n)
		{
		//approximate pi
			
			pi = pi + 4*(pow(-1,n))/(2*n-1);
		n++;
		}




		//display result
		cout << "\nTHE APPROXIMATION OF PI TO  "
			 <<	max_n << " DIGITS IS " << pi << endl;
			pi = 0;
			n = 0;

		//prompt user to enter again
		cout << "ENTER AGAIN? (y/n)\n";
		cin >> ans ;
		

		//end do-while loop
	}while (ans == 'y' || ans == 'Y');	

	//set precision to six decimals
	/*cout.setf(ios::fixed);
	cout.setf(ios::showpoint);
	cout.precision(6);*/		

	return 0;
}
Last edited by LuciWiz : 26-Nov-2005 at 04:47. Reason: Please insert your C++ code between [c++] & [/c++] tags
  #2  
Old 25-Nov-2005, 21:38
green lantern green lantern is offline
New Member
 
Join Date: Nov 2005
Posts: 5
green lantern is on a distinguished road

Re: C++ exponent help please!!!!!


oops forgot to pose question, here it is
I am unable to get the power function to work. please help!!! I have tried different number types and formats.

I am trying to use this equation ...

pi = pi + 4*pow(-1.0,n)/(2*n+1); or in other words
pi = pi + (4* (-1)^n) / (2*n -1); or in other words
pi equals pi plus 4 times negative one to the n power all devided by
quantity 2 times n minus one

this is my program...
  #3  
Old 25-Nov-2005, 22:33
kobi_hikri's Avatar
kobi_hikri kobi_hikri is offline
Regular Member
 
Join Date: Apr 2005
Location: Israel
Posts: 431
kobi_hikri has a spectacular aura aboutkobi_hikri has a spectacular aura about

Re: C++ exponent help please!!!!!


Hey.

I did some changes only so that your code will compile on my machine, but notice that I declared your globals inside "int main". Why did you declare them as globals ? is there a special reason ?

And to business :
1. You are not approximating PI correctly, but you probably understand this by now. Notice the output you get before and after each iteration of your PI approximation loop.
This is what I got for n = 4 :

Code:
ENTER THE NUMBER OF DECIMALS TO WHICH APPROXIMATE PI 4 Values BEFORE Iteration : Approximation :-4 PI :0 Value After Iteration : PI :-4 Values BEFORE Iteration : Approximation :-4 PI :-4 Value After Iteration : PI :-8 Values BEFORE Iteration : Approximation :1.33333 PI :-8 Value After Iteration : PI :-6.66667 Values BEFORE Iteration : Approximation :-0.8 PI :-6.66667 Value After Iteration : PI :-7.46667 Values BEFORE Iteration : Approximation :0.571429 PI :-7.46667 Value After Iteration : PI :-6.89524 THE APPROXIMATION OF PI TO 4 DIGITS IS -6.89524 ENTER AGAIN? (y/n) n Press any key to continue

with this code :

CPP / C++ / C Code:

//import packages
#include <cmath>
#include <stdio.h>
#include <cstdlib>
#include <iostream>
using namespace std;

//start main program
int main(int argc, char *argv[])
{
	//declare and initialize variables
	char ans = 'y';
	double n = 0;
	double max_n = 0;
	double pi = 0;

	//start loop
	do
	{
		//prompt user for the number of decimals to which
		//approximate pi
		cout << "ENTER THE NUMBER OF DECIMALS TO WHICH APPROXIMATE PI ";
		cin >> max_n;

		while (n <= max_n)
		{
			//approximate pi
			cout << "Values BEFORE Iteration : " << endl;
			cout << "Approximation :" << 4*(pow(-1,n))/(2*n-1) << endl;
			cout << "PI :" << pi << endl;
			pi = pi + 4*(pow(-1,n))/(2*n-1);
			cout << "Value After Iteration : " << endl;
			cout << "PI :" << pi << endl;
			n++;
		}

		//display result	
		cout << "\nTHE APPROXIMATION OF PI TO "
		<< max_n << " DIGITS IS " << pi << endl;
		pi = 0;
		n = 0;

		//prompt user to enter again
		cout << "ENTER AGAIN? (y/n)\n";
		cin >> ans ;


	//end do-while loop
	}while (ans == 'y' || ans == 'Y');

	//set precision to six decimals
	/*cout.setf(ios::fixed);
	cout.setf(ios::showpoint);
	cout.precision(6);*/

	return 0;
}


Check the calculation.

Best Regards,
Kobi.

[edit]
Try this link : PI digits
[/edit]
__________________
It's actually a one time thing (it just happens alot).
  #4  
Old 26-Nov-2005, 08:12
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,311
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: C++ exponent help please!!!!!


Quote:
Originally Posted by green lantern
.

I am trying to use this equation ...

pi = pi + 4*pow(-1.0,n)/(2*n+1); or in other words
pi = pi + (4* (-1)^n) / (2*n -1); or in other words
pi equals pi plus 4 times negative one to the n power all devided by
quantity 2 times n minus one

First let's make sure everyone understands the formula:

The value of pi can be expressed as the sum of an infinite series. It's kind of hard to write mathematical notation with text, but I will try:

pi is equal the sum of an infinite series:

pi = 4 - 4/3 + 4/5 - 4/9 + 4/11 -...

The "..." indicates to "continue in the same manner". What the heck does that mean? It means that we would like a general expression for the n'th term.


A little examination of the series allows us to observe that, if the first term was for n = 0, and the second term was for n = 1, then the nth term, in general, can be expressed as

4.0 * (-1 to the power n)/(2*n - 1)

(Which is kind of what you wrote in your post.)

Note that we could write that "pi = 3.14159...". That's also an infinite series, but in this case, the "..." doesn't tell us much about what "in the same manner" can mean.

Of course we can't calculate the sum of all of the terms of an infinite sequence in a finite amount of time, so we try to find an approximate value of the sum by stopping after a finite number of terms.

Whenever we do something like this, the first question(s) we should ask is/are: Is the formula (the infinite series) correct? Does the series converge? (Not all infinite series have a partial sum that converges to a fixed number as n goes to infinity.) Does it converge to pi?

I'll leave proof of this to the mathematicians. We might be able to test it with a program (that is write a program that calculates lots of terms), but we can't prove it with a program (at least not with a program that just adds up a bunch of terms).

The next question should always (always) be: If I stop after a certain number of terms, how can I know how good is my approximation? If we can't answer this question, then why bother to calculate at all?

Well, you say, if I know the value of pi, then I can calculate the error at each step. That's true, and can give insight to the properties of this infinite series (how fast does it converge), but it's kind of cheating. (If we know the value of pi, then why bother with the series at all.)

In general, in order for an approximation of any kind to be useful, we would like to know some kind of upper bound for the error.

This series is convergent and the terms have alternating signs, and there is a theorem that holds for such series:

The absolute value of the error is less than or equal to the absolute value of the first neglected term.

This absolutely astounding fact makes it possible for us to calculate an approximation to pi and know how close we are without even knowing what the value of pi is to start with(!) Maybe you aren't astounded, but I am completely blown away by the awesome power of mathematics to be able to let us do such things.

So, if we want to calculate the value to two correct decimal places, we can quit the calculations when we see that the absolute value of the next term is less tnan or equal to 0.005. (Since, if the error is less than half a unit in the second decimal place, the approximate value can be rounded to two correct decimal places.)

If we want the value to three correct decimal places, we keep adding until the absolute value of the next term is less than or equal to 0.0005. etc.

Now here's how you can calculate partial sums of an infinite series:

Code:
Suppose we have an int variable, n and a double variable sum Suppose we have a double variable, tolerance that represents the maximum absolute error that is acceptable. (For example tolerance = 0.005.) 1. set n = 0; set sum = 0; 2. repeat the following loop term = 4 * ((-1) to the power n) / (2 * n + 1) if the absolute value of term is less than or equal to tolerance, break out of the loop sum = sum + term n = n + 1 continue the loop 3. Print the value of the sum (maybe print the number of terms, n, and the absolute value of the first neglected term).

From a programming point of view, there is no guarantee that the loop will ever end (due to an error in the formula, or perhaps due to roundoff error), so we always put a limit on the number of times that the loop will ever execute.

So, we have a variable, say max_iterations, and we arbitrarily set this to some number, say 10000. If we find that the results are not within our tolerance after max_iterations, we can look at what happened. If the tolerance was unrealistically small, we might increase it. If it looks like things are going OK, but we need more iterations, we can increase max_iterations and run it again.

Then the program becomes:

Code:
1. set n = 0, set sum = 0, se 2. repeat the following loop as n goes from 0 to max_iterations term = 4 * ((-1) to the power n) / (2 * n + 1) if the absolute value of term is less than or equal to tolerance, break out of the loop sum = sum + term continue the loop

A further programming note: using the power function to calculate values powers of -1 is not really a good way to do it, and I have found some compilers that don't like negative values as the first argument, and there are better ways. But for now, you can try a program based on this pseudo code and see how it comes out.

You can actually calculate (with pencil and paper or in the program) how many terms the program should need in order to get a flavor of how fast or slow the convergence is. For example after 100 terms, the absolute value of the next term is about 0.02. (So lots more than 100 terms are required to get two correct decimal places.)


Regards,

Dave

"The purpose of computing is insight, not numbers."
---Richard W. Hamming

"Everything is made up of little numbers, whizzing around so
fast that they become stuff."
---Terry Pratchett
in The Truth
Last edited by davekw7x : 26-Nov-2005 at 08:56.
 
 

Recent GIDBlogProblems with the Navy (Officers) by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
help in c++ recursive functions vinch C++ Forum 7 04-Jan-2006 12:22

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 05:16.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.