Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate PI in C#?

Tags:

c#

pi

How can I calculate the value of PI using C#?

I was thinking it would be through a recursive function, if so, what would it look like and are there any math equations to back it up?

I'm not too fussy about performance, mainly how to go about it from a learning point of view.

like image 711
GateKiller Avatar asked Sep 02 '08 12:09

GateKiller


People also ask

How do you print the value of pi?

const long double pi = acosl(-1.0L); printf("%. 20Lf\n", pi);

What is the value of pi by supercomputer?

But that's an approximation. It's 3.1415926535, and it goes on forever.


1 Answers

If you want recursion:

PI = 2 * (1 + 1/3 * (1 + 2/5 * (1 + 3/7 * (...)))) 

This would become, after some rewriting:

PI = 2 * F(1); 

with F(i):

double F (int i) {     return 1 + i / (2.0 * i + 1) * F(i + 1); } 

Isaac Newton (you may have heard of him before ;) ) came up with this trick. Note that I left out the end condition, to keep it simple. In real life, you kind of need one.

like image 138
wvdschel Avatar answered Sep 19 '22 18:09

wvdschel