473,387 Members | 3,820 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

approximating pi

Hi, im writing a prog to approximate pi as im teaching myself c++. I
was just wondering if i wanted to calculate pi to a certain tolerance,
say like (pi - .001) or some other tolerance, what kind of loop
structure can i use to go about this. I have the algorithm that
calculates pi already programed in, ie 4(1-1/3+1/5...). Any help would
be great! Thanks.

Jul 23 '05 #1
7 7490

"bryo1001" <br******@excite.com> wrote in message
news:11*********************@l41g2000cwc.googlegro ups.com...
Hi, im writing a prog to approximate pi as im teaching myself c++. I
was just wondering if i wanted to calculate pi to a certain tolerance,
say like (pi - .001) or some other tolerance, what kind of loop
structure can i use to go about this. I have the algorithm that
calculates pi already programed in, ie 4(1-1/3+1/5...). Any help would
be great! Thanks.


This is not a C++ question, really. In whatever language you use, your loop
will be alternately adding or subtracting 4/(1+2k), right? Well, when
4/(1+2k) (ignoring the sign) is less than your tolerance value, drop out of
the loop. Because each term you're adding alternates sign (zeroing in on
the "true" value) and is smaller than the previous one, you can guarantee
that if the current term is less than the tolerance value, you must be
within that tolerance already.

-Howard

Jul 23 '05 #2
Approximating pi is much easir defined a a function rather than a
variable.

Consider your high school trigonometry.

pi = 180 degrees
pi/2 = 90 degrees
pi/4 = 45 degrees

x * x + y * y = r * r
tan(theta) = sin(theta) / cos(theta) = (r * sin(theta)) / (r *
cos(theta)) = y/x
where
x = r * cos(theta)
y = r * sin(theta)
where r is the radius, theta is an angle in radians

tan(theta) = y/x if and only if theta = arctan(y/x)
arctan is the inversere tangent. C++ calls it atan2(y,x)

If in a 45-45-90 right triangle, x = 1 and y = 1, then r = sqrt(2)

However, arctan(1/1) = pi/4

Therefore pi = 4 * arctan(1/1)

In C++, you want to do the following

#include <cmath>

double my_pi(void){return (4*atan2(1));};

PI might already be declared in the math libarary, so you should give
it a different name.

On this note, how would I define my own functions for arctangent and
square root in C++?

Jul 23 '05 #3
You have to understand that 1 - 1/3 + 1/5 will suffer round off errors
because the way floating point numbers are stored on a computer.

So the "certain tolerance" you want to calculate pi to is limited by
your computer.

Please consider using a arbitary precision library like say

http://www.swox.com/gmp/

to go beyond your computer limits

Jul 23 '05 #4
#include <stdlib.h>
#include <stdio.h>
long a=10000,b,c=2800,d,e,f[2801],g;
int main()
{
for(;b-c;f[b++]=a/5 );
for(; d=0,g=c*2; printf("%.4d",e+d/a),e=d%a,c-=14 )
for(b=c; d+=f[b]*a,f[b]=d%--g,d/=g--,--b; d*=b);
return 0;
}

Jul 23 '05 #5
That's amazing!
uououo wrote:
#include <stdlib.h>
#include <stdio.h>
long a=10000,b,c=2800,d,e,f[2801],g;
int main()
{
for(;b-c;f[b++]=a/5 );
for(; d=0,g=c*2; printf("%.4d",e+d/a),e=d%a,c-=14 )
for(b=c; d+=f[b]*a,f[b]=d%--g,d/=g--,--b; d*=b);
return 0;
}


Jul 23 '05 #6
bryo1001 wrote:

Hi, im writing a prog to approximate pi as im teaching myself c++. I
was just wondering if i wanted to calculate pi to a certain tolerance,
say like (pi - .001) or some other tolerance, what kind of loop
structure can i use to go about this. I have the algorithm that
calculates pi already programed in, ie 4(1-1/3+1/5...). Any help would
be great! Thanks.


You could use this general iteration structure:

double LastValue = Initial_Value;
double ThisValue;

do {
LastValue = ThisValue;
// calculate a new ThisValue
} while( fabs( ThisValue - LastValue ) < Tolerance );

// do something with the calculated value

The idea is to compare the calculated value in the current loop
iteration with the calculated value in the previous loop iteration.
That's the purpose of 'LastValue' and 'ThisValue'. If this difference
is small enough to be acceptable, the loop terminates.

Now that you can do this, can you calculate pi using random numbers?

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 23 '05 #7
Bushido Hacks wrote:

On this note, how would I define my own functions for arctangent and
square root in C++?


If efficiency is not your concern:
For square root you could eg. use the 'Newton method' to
solve for roots of the equation

2
x - a = 0

(where x denotes the unknown square root and a denotes the
number to get the square root from: x = sqrt(a) )

The Newton method works by calculating

f(x)
x = x - -------
n+1 n f'(x)

2
f(x) = x - a
f'(x) = 2x

Thus
x * x - a
n n
x = x - ---------------
n+1 n 2 * x
n

eg. a = 5

x = 2 (just choose a reasonable number)
0

x = 2.125
1

x = 2.2389705
2
As for calculating arctangent. I guess a Taylor expansion or something like
that could be done.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 23 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: Alan Little | last post by:
Is this something that has ever been suggested, discussed, debated and/or considered? By subroutine I mean a chunk of code that can be called like a function but which executes in the global space....
72
by: Wim Vanhoof | last post by:
Dear all, I would like to announce that the department of computer science of the University of Namur, Belgium, is seeking a post-doctoral researcher for a one-year fellowship in the area of ...
2
by: Grant Edwards | last post by:
I've been looking for some way to approximate scattered 3D data points in Python. The data doesn't seem to be amenable to fitting functions like polymials, so I may have to use something more...
0
by: PeteCresswell | last post by:
I've got two tree views: 1) A tree of codes like: States AK Alaska AL Alabama ... UT Utah OR
2
by: ruben | last post by:
Hi: After upgrading 7.4.2 to 7.4.5 quite smoothly in a Red Hat 8.0 box, we are having intermitent issues with certain online PHP transactions, returning this error: "Warning: pg_exec() query...
0
by: api | last post by:
I've got a problem. I'm trying to simplify a path in SVG, namely approximate arcs by cubics. Could anybody of you direct me how to find intermediate points? The path's direction matters. Piotr
8
by: DOn1980 | last post by:
The value ex can be approximated by the sum 1 + x + x2/2! + x3/3! + … + xn/n! Write a program that takes a value x as input and outputs this sum for n taken to be each of the values 1 to 100. The...
9
by: peter | last post by:
Hi, this is not stinky bait. If you take it that way, please dont respond.. I have been away from UNIX software for quite awhile and want to get back into it. I liked "C" but Java seems like...
16
by: Erwin Moller | last post by:
Why is a binary file executable? Is any binary file executable? Is only binary file executable? Are all executable files binary? What is the connection between the attribute of binary and that of...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.