473,585 Members | 2,496 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PI equation in C

9 New Member
Hello All,

i'm currently working on a program wich asks the user to input an integer value of "n" to determine what value of the denominator in an equation for PI to work to.

this is written in c, and I have all the basic input, output, function calls etc; however, i'm relatively new to c and i'm a bit confused on how to turn the equation below into a c expression with variable input.

PI = 4(1 + 1/3 - 1/5 + 1/7 etc... (where int n is the value of the denominator to continue to)

anyone able to help? Thanks a lot!
Oct 22 '06 #1
7 4899
Banfa
9,065 Recognized Expert Moderator Expert
The thing that changes about that equation is the denominator, also remember that

PI = 4(1 + 1/3 - 1/5 + 1/7 ...) = 4 + 4/3 - 4/5 + 4/7 ...)

also I think you have you pluses and minuses the wrong way round it should be

PI = 4(1 - 1/3 + 1/5 - 1/7 ...) = 4 - 4/3 + 4/5 - 4/7 ...)


So you need a (for) loop controling the denominator. Then have a variable that is initialised to zero and for each iteration of the loop add (or subtract) another term of the series

Expand|Select|Wrap|Line Numbers
  1. INITIALISE PI to 0
  2. FOR NUMBER OF SERIES TERMS REQUIRED
  3.    ADD SERIES TERM TO PI
  4. END FOR
  5.  
Oct 23 '06 #2
volunteerguy
9 New Member
my bad on the +'s and -'s that was simply a typo...

so if i was to write a for loop something like

int PI;
int n; //number of iterations
int den_val; //denominator value

for(PI = 0; n > den_val; PI += den_val) {
/*code*/
}

and assuming that is correct, i'm still a little confused on how to incorporate the equation into the loop. I understand the 4 - 4/3 + 4/5 etc... but i'm not quite sure how to tie that into the loop and have the the +'s and -'s alternating.

i hope that makes sense, and i appreciate your help.
Oct 23 '06 #3
Banfa
9,065 Recognized Expert Moderator Expert
You loop is not quite right, also remember PI is 3.141...., try and store it in a int and it will be 3. Your loop control variable should be an int but you will need to calculate PI as a double value.

The = and - are easy, just have a boolean variable (are you using C or C++?) to maintain an indication of what to do with the next term, also note that 1 = 1/1

Expand|Select|Wrap|Line Numbers
  1. GET NUMBER OF TERMS REQUIRED nTerm
  2. SET ADD = TRUE
  3. SET PI = 0
  4.  
  5. FOR EACH REQUIRED TERM
  6.     IF ADD == TRUE
  7.         SET PI = PI + VALUE OF TERM
  8.         SET ADD = FALSE
  9.     ELSE
  10.         SET PI = PI - VALUE OF TERM
  11.         SET ADD = TRUE
  12. END FOR
  13.  
  14. PRINT PI
  15.  
Note that the nth term of the series has the value 4/(n*2-1), verify this for yourself.
Oct 23 '06 #4
volunteerguy
9 New Member
i'll give that a whirl, i see what you're getting at

i'm coding in standard C

i appreciate the help!
Oct 23 '06 #5
volunteerguy
9 New Member
so here is what i've come up with...
it seems to me like it should execute correctly, but somewhere something is causing my output to be bogus large numbers; however, it will compile... does anyone see my error?
any help will be appreciated!
Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2.  
  3. void pi(int n, double *pi_value, int *iterations); //declare function
  4.  
  5. int main (void)
  6. {
  7.     int n;                    //number of terms
  8.     int iterations;        //number of actual loop iterations in pi
  9.     double pi_value;   //computed value of pi
  10.  
  11.     printf("Please enter an odd integer n;  ")'
  12.     printf("quit with a non-positive or even integer:\n");
  13.  
  14.    /*-- Read n and display pi.  Quit with a non-positive n.  --*/
  15.    scanf("%d", &n);
  16.    while(n>0 && n%2)
  17.    {
  18.        pi(n, &pi_value, &iterations);
  19.        printf("%17d:   %0.81f with %d iterations\n", n, pi_value, iterations);
  20.        scanf("%d", &n);
  21.    }
  22.  
  23.    return(0);
  24. }  
  25.  
  26. voi pi(int n, double *pi_value, int *iterations)
  27. {
  28.     int i;
  29.     int ADD = 1 // 1 = true & 2 = false
  30.  
  31.     for(i=0; i<n; i++)
  32.     {
  33.         pi_value += (4/((n*2)-1));
  34.         ADD = 2;
  35.         break;
  36.     }
  37.     for(ADD == 2)
  38.     {
  39.         pi_value -= (4/((n*2)-1));
  40.         ADD = 1;
  41.         break;
  42.     }
  43.     (*iterations)++
  44. }
  45.  
  46.  
Oct 23 '06 #6
volunteerguy
9 New Member
please ignore the code from my previous post, i typed it in a rush and realized it had many glaring syntax errors, try this one instead...

Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2.  
  3. void pi(int n, double *pi_value, int *iterations); //declare function
  4.  
  5. int main (void)
  6. {
  7.     int n;                    //number of terms
  8.     int iterations = 0;        //number of actual loop iterations in pi
  9.     double pi_value = 0;   //computed value of pi
  10.  
  11.     printf("Please enter an odd integer n;  ")'
  12.     printf("quit with a non-positive or even integer:\n");
  13.  
  14.    /*-- Read n and display pi.  Quit with a non-positive n.  --*/
  15.    scanf("%d", &n);
  16.    while(n>0 && n%2)
  17.    {
  18.        pi(n, &pi_value, &iterations);
  19.        printf("%17d:   %0.81f with %d iterations\n", n, pi_value, iterations);
  20.        scanf("%d", &n);
  21.    }
  22.  
  23.    return(0);
  24. }  
  25.  
  26. void pi(int n, double *pi_value, int *iterations)
  27. {
  28.     int i;
  29.     int ADD = 1 // 1 = true & 2 = false
  30.  
  31.     for(i=0; i<n; i++)
  32.     {
  33.         switch(ADD) 
  34.         {
  35.            case 1:
  36.              *pi_value += (4/((n*2)-1));
  37.              ADD = 2;
  38.              break;
  39.            case 2:
  40.              *pi_value -= (4/((n*2)-1));
  41.               ADD = 1;
  42.          {   break;
  43.     }
  44.     (*iterations)++;
  45. }
  46.  
Oct 23 '06 #7
Banfa
9,065 Recognized Expert Moderator Expert
You have 5 errors (ignoreing the minor syntax errors you posted, once you have compiling code copy and paste is a good way to get it to the forum posting box).

They are all in this section of code, I am going to tell you about 4 of them. Once I have done this you should be able to find the other one by running your program.

Expand|Select|Wrap|Line Numbers
  1. void pi(int n, double *pi_value, int *iterations)
  2. {
  3.     int i;
  4.     int ADD = 1; // 1 = true & 2 = false
  5.  
  6.     for(i=0; i<n; i++)
  7.     {
  8.         switch(ADD) 
  9.         {
  10.            case 1:
  11.              *pi_value += (4/((n*2)-1));
  12.              ADD = 2;
  13.              break;
  14.            case 2:
  15.              *pi_value -= (4/((n*2)-1));
  16.               ADD = 1;
  17.          {   break;
  18.     }
  19.     (*iterations)++;
  20. }
  21.  
On a point of style it is slightly more normal to use the value 0 for false but your use of 2 does not stop the program working.
  1. Expand|Select|Wrap|Line Numbers
    1. for(i=0; i<n; i++)
    This doesn't stop the program working but I suspect it does make it so that it is not doing what you think it is doing. Note n is always odd, making me think you were asking for the highest term denominator to use, however this loop uses it as the number. Does the series always require an odd number of terms or would it work with an even number? Actually this series works with any number of terms > 0. If n = 7 the text message give the impression of creating this series

    PI = 4(1 - 1/3 + 1/5 - 1/7)

    but the code actually evaluates this

    PI = 4(1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13)

    Decide if you want to input the number of terms (change text but the loop stays the same) or the value of the maximum denominator (change loop, possible change text to to make it clear what is being input).
  2. Expand|Select|Wrap|Line Numbers
    1. (*iterations)++;
    You have put it outside the loop, it only ever executes once for each function call, with the current loop it will always end up equal to n.
  3. Expand|Select|Wrap|Line Numbers
    1. *pi_value -= (4/((n*2)-1));
    You have used the variable n, this is the number of terms to use, not the current term. You need tobase the calculation on the variable i which is the one that changes. But note a straight swop will not work because the initial value of i is 0. You have (correctly) used the formula for the xth term 4 / ((x*2)-1), so the first term is 4 / ((1*2)-1), but your control variable value does not start at 1 ir starts at 0, you need to add 1 to it 4 / (((i+1)*2)-1), a little algibra will so that this is equal to 4 / ((i*2)+1)
  4. Expand|Select|Wrap|Line Numbers
    1. *pi_value -= (4/((i*2)+1));
    *pi_value is a floating point type but i (or n) are int and 4, 2 and 1 are integer constants.. The calculation is done in integer arithmatic and then converted to a double. In integer arithmatic all decimal places are dropped, the first term evaluates to 4/1=4 the second to 4/3=1 and all further terms evaluate to 0 giving a result of 3. You need to force the compiler to use floating point arithmatic.

    You can either cast the controlling variable to double
    Expand|Select|Wrap|Line Numbers
    1. *pi_value -= (4/(((double)i*2)+1));
    Using floating point constants instead of integer constants
    Expand|Select|Wrap|Line Numbers
    1. *pi_value -= (4./((i*2.)+1.));
Like I said there is 1 more error, see if you can find it (hint try 2 calculations in a row).

And finally 1 more point of style
Expand|Select|Wrap|Line Numbers
  1. printf("%17d:   %0.81f with %d iterations\n", n, pi_value, iterations);
A double only has a precision of 15 decimal places, asking it for 81 is wishful thinking, also if you don't want a field width just don't specify one, no need to set it to 0 so this line would be better as

Expand|Select|Wrap|Line Numbers
  1. printf("%17d:   %.15f with %d iterations\n", n, pi_value, iterations);
You can test this, set the 15 to a 16, the last digit will always be 0
Oct 24 '06 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

4
6045
by: Sven Dzepina | last post by:
Hello people =) Has somebody a nice script, which can solve equations ? It would be super, if someone has an idea where I can get such a script / code in php. Thanks. Gretting!
1
1627
by: Russell Blau | last post by:
This is not really a Python question, but it does relate to a Python program I'm working on, so this seems like as good a place as any to ask for suggestions ... I'm working on a GUI application that lets the user enter an alegbraic equation and displays a nicely-formatted representation of the same equation (and then maybe does other stuff...
20
8684
by: Brian Kazian | last post by:
Here's my problem, and hopefully someone can help me figure out if there is a good way to do this. I am writing a program that allows the user to enter an equation in a text field using pre-existing variables. They then enter numerical values for these variables, or can tell the program to randomize the values used within a certain bounds....
9
8912
by: Stud Muffin | last post by:
Hey Basically, I'm trying to take objects created in microsoft word using equation editor (for creating clean looking math/physics equations) and putting them into some sort of webpage format. But they come out grossly unalligned and ugly when I try to directly copy and paste into microsoft frontpage 2000. Few things I could do is place...
5
3067
w33nie
by: w33nie | last post by:
My table is pretty well complete, but I would prefer it if the value for Points could be turned into a mathematical equation, and this equation would use the data from the other fields in the table to achieve a value. I want this done in phpMyAdmin 2.7, if possible, so that when I change the values in other fields, the Points variable changes,...
6
14833
by: Trev17 | last post by:
Hello, I am new to C++ and i have tried for several hours to make a program my teacher has given me as a lab. Here is the Lab question: the roots of the quadratic equation ax^2 + bx + c = 0, a cannot equal 0 are given by the following formula -b + or - square root of (b^2 - 4ac) / 2a. If b^2 - 4ac = 0 then equation has a single root. if...
10
2358
by: Constantine AI | last post by:
Hi i am having a little problem with an equation function that was created from all your help previously. The function works fine itself but with a small glitch within it. Here is the function code. Public Function fCalcEquation(strEquation As String) As Long Dim MyDB As DAO.Database Dim rstParameters As DAO.Recordset Dim...
2
3758
by: phoenix1990 | last post by:
so i have an entry frame where i want to input an equation, and i need to turn the string into an actual equation in terms of x. so that i can plot it on a canvas. i already know how to make the entry frame, and how to extract the string equation that was inputed. the only problem i'm having is converting it into an actual equation. e.g. the...
0
1469
by: prashantdixit | last post by:
Hi, I am trying to generate Linear Trendline Equation for a graph using VBA in Excel 2007. I am able to do it. However It always generate trendline equation in "General" Format. And i want to display linear trendline equation oin graph in "scientific notation" upto 5 decimal places using VBA code. The code which i have written for...
0
7908
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7836
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8199
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8336
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6606
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5710
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5389
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3835
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3863
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.