loading

C++ programming...?

Hi all. i know a bit of c++. And I want to make a simple program that calculates Pi. Now, I want it to have the user input the number of decimal point thingies... and let it do the rest. BUT, it must be stoppable no matter how HUGE a number the put in... and im 12, so please try to make it as easy as possible. THANKS!

sort by: active | newest | oldest
Ziviz5 years ago
It looks like Chris Hills made something like what you want: http://www.codeproject.com/KB/recipes/CRHpi.aspx

I think what you have to do is replace the CRHCalculatePiClass::calculate(void) function from the link above, with:

CRHCalculatePiClass::calculate(void){
for (;;){
//This alteration should keep the result accurate even if you end it early
if (term5m!=zero){
do5term();
}
if (term239m!=zero){
do239term();
}
if (term5m==zero&&term239m==zero){
break;
}
//And this one should allow you to end the program early by pressing the e key
if (Console::KeyAvailable&&Console::ReadKey().Key==ConsoleKey::E){
break;//Early end
}
}
}

Unfortunatly I am not very C++ savvy. Not sure I can help much more than this.
sci4me (author)  Ziviz5 years ago
Ok.. I got this:

#include
#include
#include // required for rand function
#include // required for srand seed with time
#include // required for square root calculation

int main(int nNumberofArgs, char* pszArgs[])
{
srand (time(NULL)); // uses time to seed random generator
int nCArea = 0;
int nGuess = 1000000000;
double dPi;
cout << "Running 1,000,000,000 iterations to calculate Pi.\n";
for (int nI=1; nI<=nGuess; nI++)
{
float fRandomx = rand(); // creates a random number, rand only returns integers so must convert to float to get 0 - 1 range
float fTotalx = RAND_MAX; // maximum value of random number
float fX = fRandomx/fTotalx; // crates a random zero to 1 fraction
float fRandomy = rand(); // creates a random number, rand only returns integers so must convert to float to get 0 - 1 range
float fTotaly = RAND_MAX; // maximum value of random number
float fY = fRandomy/fTotaly; // crates a random zero to 1 fraction
double dDistance = sqrt((fX*fX)+(fY*fY)); // distance from (0,0) equation
if (dDistance <= 1) {nCArea++;} // counts distances within the quarter circle
double dCArea = nCArea;
double dI = nI;
dPi = 4*dCArea/dI;
}
printf("\nPi = %.6f\n", dPi);

system("pause");
return 0;
}

But, I decided to go with Visual Basic Express 2010. How can I convert this? i have a GREAT Program, I just need to convert this. Then, my dreams will come true! PLEASE REPLY ASAP!!! IM EXCITED!
Ziviz sci4me5 years ago
Here is my conversion of the code you posted. I was able to remove some of the code, as it is already handled. I also added a small if statement that informs you how close the program is to finishing. Due to the nature of pi, and this algorithm, at the end of the 1000000000 iterations it is only accurate up to about 3.14159, and even then, only sometimes. For higher accuracy you can increase iterations, but past a certain point, you are going to have to start using larger number types (like orksecurity mentioned)

Sub Main()
Dim random As New Random() 'Automatically uses date as seed
Dim nCArea As Long = 0 '# of points that landed inside the quarter circle
Dim nGuess As Long = 1000000000 'number of iterations to run
Dim dPi As Double = 0 'finished pi
Console.WriteLine("Running " + nGuess.ToString() + " iterations to calculate Pi.")

For nl = 1 To nGuess
Dim dX As Double = random.NextDouble() 'automatically returns a fraction from 0 to 1
Dim dY As Double = random.NextDouble() 'again, fraction from 0 to 1
Dim dDistance As Double = Math.Sqrt((dX * dX) + (dY * dY)) 'Distance formula
If dDistance <= 1 Then
nCArea += 1 'if inside circle, increment nCArea
End If

If nl Mod (nGuess / 100) = 0 Then 'this entire statement informs the user pi and % before complete
Console.Clear() 'Empty window (Prevent a bagillion lines from piling up in the console)
Console.WriteLine((nl * 100 / nGuess).ToString() + "%") 'Tell user % complete
dPi = 4 * nCArea / nl 'calculate pi as of now
Console.WriteLine("PI=" + dPi.ToString()) 'show user current pi
End If

Next nl
dPi = 4 * nCArea / nGuess 'calculate finished pi
Console.Clear() 'Empty window (Prevent a bagillion lines from piling up in the console)
Console.WriteLine("PI=" + dPi.ToString()) 'tell user completed pi
Console.ReadKey() 'pauses program until user presses "enter"
End Sub
sci4me (author) 5 years ago
https://www.instructables.com/answers/Visual-Basic-Code/
pi can be calculated with extremem acuracy with this super complicated equation that takes years maybe even days to complete!

get ready

22 / 7= Pi
orksecurity5 years ago
Websearch "monte carlo calculation of pi" for an algorithm which should be within your current programming skills. (We wrote a Basic version of that as part of my first formal programming class.)

There are better ways to calculate pi, but they require much fancier math. Again, websearching will find some of those alternatives, as will hitting a library and looking at programming textbooks

If you want a huge number of digits, you will need to do thecalculations using an extended-precision library ("Big Integers" and "Big Floats" rather than longs and doubles). And any of the algorithms will take exponentially longer time as the number of digits desired increases, so "a huge number" may take a gawdawful long time, even on a fast machine.

Have fun!

(3.1415926535897932384626....)
sci4me (author)  orksecurity5 years ago
im 12 and dont know how to implament that... is there any documentation on implamenting it into c++... I really would like a simple example... just a snippet of what to do in the code... Thanks for your time!
Monte Carlo Method:

The area of a circle is pi times the square of the radius, right? So the area of a circle of radius 1 is pi, and the area of a quarter-circle of radius 1 is 1/4 of pi.

So: Generate pairs of random numbers between 0 and 1. (This does require that you have a good random number generator.) Treat those as X and Y coordinates within a 1x1 square. Determine whether they're inside or outside a quarter-circle of radius 1 with its center at 0,0, using the right-triangle rule: if x squared plus y squared is <= 1 the point is inside, if it's > 1 the point is outside.

Keep throwing these random-number "darts" at the 1x1 square and keep track of how many are inside the circle. Eventually -- assuming your random number generator is good -- the ratio of points inside the circle to the total number of darts will approach the ratio of the area of the quarter-circle to the area of the square, or 1/4 pi to 1.. from which you can obtain pi.

The approximation will become progressively better as you throw more darts, modulo some sampling noise. If you keep track of the difference between each new ratio as you throw the darts, you'll see that the higher digits stop changing before the lower ones do. Stop when this difference is small enough that you think a sufficient number of digits have accurately reached their final value.

As I say, websearching will find much more detailed discussion and code samples. I've already saved you a lot of work by pointing you in the right direction; the rest of the homework assignment is your responsibility.