3 Simple Ways to
Share What You Make

With Instructables you can share what you make with the world — and tap into an ever-growing community of creative experts.

PhotosPhotos

Share one or more photos of a project, recipe, or whatever you've made, quickly and easily.

Step by StepStep-By-Step

Share your step-by-step photos with text instructions of what you made so others can do it too!

VideoVideo

Share your how-to video. You'll need your embed code from a video site such as YouTube.

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!

9 answers
sort by: active | newest | oldest
Jun 3, 2011. 8:44 PMZiviz says:
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.
Jun 8, 2011. 9:53 PMZiviz says:
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
Jun 4, 2011. 7:40 PMjpoopdog says:
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
Jun 3, 2011. 5:50 PMorksecurity says:
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....)
Jun 3, 2011. 9:35 PMorksecurity says:
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.

Pro

Get More Out of Instructables

Already have an Account?

close

All Steps Viewing
View all steps of an Instructable on the same page when you're a Pro Member.

Upgrade to Pro today!