4

To calculate Pi you can use the equation pi/4=1-(1/3)+(1/5)-(1/7)+... Multiply it by 4 and you get Pi I created a formula to calculate each step of the equation relative to its position 1/(2n-1) and wrote code for it

#include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { double p = 0; double pi = 0; int j = 1; do { if (j % 2 == 1) { p = p + (1 / (2 * j - 1)); } else { p = p - (1 / (2 * j - 1)); } pi = p * 4; printf("%lf\n", pi); j++; } while (j < 10); return (EXIT_SUCCESS); } 

but it is only putting out 4.0000 Why? I cant find the mistake I made.

5
  • 3
    Change p = p + (1 / (2 * j - 1)); to p = p + (1.0 / (2 * j - 1)); Commented Apr 20, 2018 at 10:16
  • 4
    (1 / (2 * j - 1)) is an integer division Commented Apr 20, 2018 at 10:16
  • 2
    pi/4=1-(1/3)+(1/5)-(1/7)+... This formula converges extremely slowly. This is the worst method to compute pi. Commented Apr 20, 2018 at 10:17
  • 1
    @liliscent my goal is this slow conversion. Im going to plot this afterwards. Commented Apr 20, 2018 at 10:47
  • the first problem I see is that ALL the literals are integer rather than double. I.E. rather than 1 use 1.0 rather than 2 use 2.0 etc. As it is, all the calculations are being performed with integers. When performing calculations with integers, the fraction is dropped Commented Apr 20, 2018 at 19:50

2 Answers 2

4

In the statement p = p + (1 / (2 * j - 1)); expression (1 / (2 * j - 1) yields in integer. To get expected result make either operand as floating type i.e either 1.0 or (float)(2 * j - 1)

Replace the statement

p = p + (1 / (2 * j - 1));/* 1/(2*j-1) results in integer, you won't get expected result */ 

with

p = p + (1. / (2 * j - 1));/* 1. means making floating type */ 
Sign up to request clarification or add additional context in comments.

Comments

4

In your expression

1 / (2 * j - 1) 

both operands of / are of type int, therefore it performs an integer division, which truncates the fraction. If you want to perform a real division, make sure at least one of the operands has a floating point type. You can easily achieve this here by writing

1.0 / (2 * j - 1) 

A numeric constant containing a decimal point (and without a suffix) is of type double in C.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.