Pi attitude. Calculation of the Nth sign of Pi without calculating the previous ones

On March 14, a very unusual holiday is celebrated all over the world - Pi Day. Everyone has known it since school days. Students are immediately explained that the number Pi is a mathematical constant, the ratio of the circumference of a circle to its diameter, which has an infinite value. It turns out that a lot of interesting facts are connected with this number.

1. The history of number has more than one millennium, almost as long as the science of mathematics exists. Of course, the exact value of the number was not immediately calculated. At first, the ratio of the circumference to the diameter was considered equal to 3. But over time, when architecture began to develop, a more accurate measurement was required. By the way, the number existed, but it received a letter designation only at the beginning of the 18th century (1706) and comes from the initial letters of two Greek words meaning “circumference” and “perimeter”. The mathematician Jones endowed the number with the letter "π", and she firmly entered mathematics already in 1737.

2. In different eras and among different peoples, the number Pi had different meanings. For example, in ancient Egypt it was 3.1604, among the Hindus it acquired the value of 3.162, the Chinese used the number equal to 3.1459. Over time, π was calculated more and more accurately, and when computer technology appeared, that is, a computer, it began to have more than 4 billion characters.

3. There is a legend, more precisely, experts believe that the number Pi was used in the construction of the Tower of Babel. However, it was not the wrath of God that caused its collapse, but incorrect calculations during construction. Like, the ancient masters were mistaken. A similar version exists regarding Solomon's temple.

4. It is noteworthy that they tried to introduce the value of Pi even at the state level, that is, through the law. In 1897, a bill was drafted in the state of Indiana. According to the document, Pi was 3.2. However, scientists intervened in time and thus prevented an error. In particular, Professor Purdue, who was present at the legislative assembly, spoke out against the bill.

5. It is interesting that several numbers in the infinite sequence Pi have their own name. So, six nines of Pi are named after an American physicist. Once Richard Feynman was giving a lecture and stunned the audience with a remark. He said he wanted to learn the digits of pi up to six nines by heart, only to say "nine" six times at the end of the story, hinting that its meaning was rational. When in fact it is irrational.

6. Mathematicians around the world do not stop doing research related to the number Pi. It is literally shrouded in mystery. Some theorists even believe that it contains a universal truth. In order to share knowledge and new information about Pi, they organized the Pi Club. Entering it is not easy, you need to have an outstanding memory. So, those wishing to become a member of the club are examined: a person must tell as many signs of the number Pi from memory as possible.

7. They even came up with various techniques for remembering the number Pi after the decimal point. For example, they come up with whole texts. In them, words have the same number of letters as the corresponding digit after the decimal point. To further simplify the memorization of such a long number, they compose verses according to the same principle. Members of the Pi Club often have fun in this way, and at the same time train their memory and ingenuity. For example, Mike Keith had such a hobby, who eighteen years ago came up with a story in which each word was equal to almost four thousand (3834) first digits of pi.

8. There are even people who have set records for memorizing Pi signs. So, in Japan, Akira Haraguchi memorized more than eighty-three thousand characters. But the domestic record is not so outstanding. A resident of Chelyabinsk was able to memorize only two and a half thousand numbers after the decimal point of Pi.


"Pi" in perspective

9. Pi Day has been celebrated for more than a quarter of a century, since 1988. Once, a physicist from the Popular Science Museum in San Francisco, Larry Shaw, noticed that March 14 was spelled the same as pi. In a date, the month and day form 3.14.

10. Pi Day is celebrated not only in an original way, but in a fun way. Of course, scientists involved in the exact sciences do not miss it. For them, this is a way not to break away from what they love, but at the same time to relax. On this day, people gather and cook different goodies with the image of Pi. Especially there is a place for confectioners to roam. They can make pi cakes and similarly shaped cookies. After tasting the treats, mathematicians arrange various quizzes.

11. There is an interesting coincidence. On March 14, the great scientist Albert Einstein was born, who, as you know, created the theory of relativity. Be that as it may, physicists can also join in the celebration of Pi Day.

Recently, there is an elegant formula for calculating pi, which was first published in 1995 by David Bailey, Peter Borwein and Simon Pluff:

It would seem: what is special about it - there are a great many formulas for calculating Pi: from the school Monte Carlo method to the incomprehensible Poisson integral and Francois Vieta's formula from the late Middle Ages. But it is this formula that you should pay special attention to - it allows you to calculate the nth sign of pi without finding the previous ones. For information on how it works, as well as for ready-made C code that calculates the 1,000,000th character, I ask for a habrakat.

How does the algorithm for calculating the Nth sign of Pi work?
For example, if we need the 1000th hexadecimal digit of pi, we multiply the whole formula by 16^1000, thereby turning the factor in front of the brackets into 16^(1000-k). When exponentiating, we use the binary exponentiation algorithm or, as will be shown in the example below, exponentiation modulo . After that, we calculate the sum of several terms of the series. Moreover, it is not necessary to calculate a lot: as k increases, 16 ^ (N-k) quickly decreases, so that subsequent terms will not affect the value of the desired digits). That's all magic - ingenious and simple.

The Bailey-Borwein-Pluff formula was found by Simon Pluff using the PSLQ algorithm, which was included in the Top 10 Algorithms of the Century list in 2000. The PSLQ algorithm itself was in turn developed by Bailey. Here is a Mexican series about mathematicians.
By the way, the running time of the algorithm is O(N), the memory usage is O(log N), where N is the ordinal number of the desired character.

I think it would be appropriate to give the C code written directly by the author of the algorithm, David Bailey:

/* This program implements the BBP algorithm to generate a few hexadecimal digits beginning immediately after a given position id, or in other words beginning at position id + 1. On most systems using IEEE 64-bit floating- point arithmetic, this code works correctly so long as d is less than approximately 1.18 x 10^7. If 80-bit arithmetic can be employed, this limit is significantly higher. Whatever arithmetic is used, results for a given position id can be checked by repeating with id-1 or id+1, and verifying that the hex digits perfectly overlap with an offset of one, except possibly for a few trailing digits. The resulting fractions are typically accurate to at least 11 decimal digits, and to at least 9 hex digits. */ /* David H. Bailey 2006-09-08 */ #include #include int main() ( double pid, s1, s2, s3, s4; double series (int m, int n); void ihex (double x, int m, char c); int id = 1000000; #define NHX 16 char chx ;/* id is the digit position.Digits generated follow immediately after id.*/ s1 = series(1, id);s2 = series(4, id);s3 = series(5, id);s4 ​​= series(6 , id); pid = 4. * s1 - 2. * s2 - s3 - s4; pid = pid - (int) pid + 1.; ihex (pid, NHX, chx); printf("position = %i\n fraction = %.15f \n hex digits = %10.10s\n", id, pid, chx); ) void ihex (double x, int nhx, char chx) /* This returns, in chx, the first nhx hex digits of the fraction of x. */ ( int i; double y; char hx = "0123456789ABCDEF"; y = fabs(x); for (i = 0; i< nhx; i++){ y = 16. * (y - floor (y)); chx[i] = hx[(int) y]; } } double series (int m, int id) /* This routine evaluates the series sum_k 16^(id-k)/(8*k+m) using the modular exponentiation technique. */ { int k; double ak, eps, p, s, t; double expm (double x, double y); #define eps 1e-17 s = 0.; /* Sum the series up to id. */ for (k = 0; k < id; k++){ ak = 8 * k + m; p = id - k; t = expm (p, ak); s = s + t / ak; s = s - (int) s; } /* Compute a few terms where k >= id. */ for (k = id; k<= id + 100; k++){ ak = 8 * k + m; t = pow (16., (double) (id - k)) / ak; if (t < eps) break; s = s + t; s = s - (int) s; } return s; } double expm (double p, double ak) /* expm = 16^p mod ak. This routine uses the left-to-right binary exponentiation scheme. */ { int i, j; double p1, pt, r; #define ntp 25 static double tp; static int tp1 = 0; /* If this is the first call to expm, fill the power of two table tp. */ if (tp1 == 0) { tp1 = 1; tp = 1.; for (i = 1; i < ntp; i++) tp[i] = 2. * tp; } if (ak == 1.) return 0.; /* Find the greatest power of two less than or equal to p. */ for (i = 0; i < ntp; i++) if (tp[i] >p) break; pt=tp; p1 = p; r = 1.; /* Perform binary exponentiation algorithm modulo ak. */ for (j = 1; j<= i; j++){ if (p1 >= pt)( r = 16. * r; r = r - (int) (r / ak) * ak; p1 = p1 - pt; ) pt = 0.5 * pt; if (pt >= 1.)( r = r * r; r = r - (int) (r / ak) * ak; ) ) return r; )
What opportunities does it give? For example: we can create a distributed computing system that calculates the number Pi and set a new record for the calculation accuracy for all Habr (which now, by the way, is 10 trillion decimal places). According to empirical data, the fractional part of the number Pi is a normal numerical sequence (although this has not yet been reliably proven), which means that sequences of digits from it can be used in generating passwords and just random numbers, or in cryptographic algorithms (for example, in hashing) . You can find a great variety of ways to use it - you just need to turn on your imagination.

You can find more information on the topic in the article by David Bailey himself, where he talks in detail about the algorithm and its implementation (pdf);

And it seems that you have just read the first Russian-language article about this algorithm in RuNet - I could not find others.

PI
The symbol PI stands for the ratio of the circumference of a circle to its diameter. For the first time in this sense, the symbol p was used by W. Jones in 1707, and L. Euler, having accepted this designation, introduced it into scientific use. Even in ancient times, mathematicians knew that calculating the value of p and the area of ​​a circle are closely related tasks. The ancient Chinese and ancient Jews considered the number p equal to 3. The value of p, equal to 3.1605, is contained in the ancient Egyptian papyrus of the scribe Ahmes (c. 1650 BC). Around 225 BC e. Archimedes, using regular 96-gons inscribed and circumscribed, approximated the area of ​​a circle using a method that resulted in a PI value between 31/7 and 310/71. Another approximate value of p, equivalent to the usual decimal representation of this number 3.1416, has been known since the 2nd century. L. van Zeulen (1540-1610) calculated the value of PI with 32 decimal places. By the end of the 17th century. new methods of mathematical analysis made it possible to calculate the value of p in many different ways. In 1593 F. Viet (1540-1603) derived the formula

In 1665 J. Wallis (1616-1703) proved that


In 1658, W. Brounker found a representation of the number p in the form of a continued fraction


G. Leibniz in 1673 published a series


Series allow you to calculate the value of p with any number of decimal places. In recent years, with the advent of electronic computers, the value of p has been found with more than 10,000 digits. With ten digits, the value of PI is 3.1415926536. As a number, PI has some interesting properties. For example, it cannot be represented as a ratio of two integers or as a periodic decimal; the number PI is transcendental, i.e. cannot be represented as a root of an algebraic equation with rational coefficients. The PI number is included in many mathematical, physical and technical formulas, including those not directly related to the area of ​​a circle or the length of an arc of a circle. For example, the area of ​​an ellipse A is given by A = pab, where a and b are the lengths of the major and minor semiaxes.

Collier Encyclopedia. - Open society. 2000 .

See what "PI NUMBER" is in other dictionaries:

    number- Reception Source: GOST 111 90: Sheet glass. Specifications original document See also related terms: 109. Number of betatron oscillations ... Dictionary-reference book of terms of normative and technical documentation

    Ex., s., use. very often Morphology: (no) what? numbers for what? number, (see) what? number than? number about what? about the number; pl. what? numbers, (no) what? numbers for what? numbers, (see) what? numbers than? numbers about what? about mathematics numbers 1. Number ... ... Dictionary of Dmitriev

    NUMBER, numbers, pl. numbers, numbers, numbers, cf. 1. A concept that serves as an expression of quantity, something with the help of which objects and phenomena are counted (mat.). Integer. Fractional number. named number. Prime number. (see simple1 in 1 value).… … Explanatory Dictionary of Ushakov

    An abstract designation, devoid of special content, of any member of a certain series, in which this member is preceded or followed by some other definite member; an abstract individual feature that distinguishes one set from ... ... Philosophical Encyclopedia

    Number- Number is a grammatical category that expresses the quantitative characteristics of objects of thought. The grammatical number is one of the manifestations of a more general linguistic category of quantity (see the Linguistic category) along with a lexical manifestation (“lexical ... ... Linguistic Encyclopedic Dictionary

    A number approximately equal to 2.718, which is often found in mathematics and science. For example, during the decay of a radioactive substance after time t, a fraction equal to e kt remains from the initial amount of substance, where k is a number, ... ... Collier Encyclopedia

    BUT; pl. numbers, villages, slam; cf. 1. A unit of account expressing one or another quantity. Fractional, integer, simple hours. Even, odd hours. Count as round numbers (approximately, counting as whole units or tens). Natural hours (positive integer ... encyclopedic Dictionary

    Wed quantity, count, to the question: how much? and the very sign expressing quantity, the figure. Without number; no number, no count, many many. Put the appliances according to the number of guests. Roman, Arabic or church numbers. Integer, contra. fraction. ... ... Dahl's Explanatory Dictionary

    NUMBER, a, pl. numbers, villages, slam, cf. 1. The basic concept of mathematics is the value, with the help of which the swarm is calculated. Integer hours Fractional hours Real hours Complex hours Natural hours (positive integer). Simple hours (natural number, not ... ... Explanatory dictionary of Ozhegov

    NUMBER "E" (EXP), an irrational number that serves as the basis of natural LOGARITHMS. This real decimal number, an infinite fraction equal to 2.7182818284590...., is the limit of the expression (1/) as n goes to infinity. In fact,… … Scientific and technical encyclopedic dictionary

    Quantity, cash, composition, strength, contingent, amount, figure; day.. Wed. . See day, quantity. a small number, no number, grow in number... Dictionary of Russian synonyms and expressions similar in meaning. under. ed. N. Abramova, M .: Russians ... ... Synonym dictionary

Books

  • Name number. Secrets of numerology. Exit from the body for the lazy. ESP Primer (number of volumes: 3), Lawrence Shirley. Name number. Secrets of numerology. Shirley B. Lawrence's book is a comprehensive study of the ancient esoteric system - numerology. To learn how to use number vibrations to…
  • Name number. The sacred meaning of numbers. Symbolism of the Tarot (number of volumes: 3), Uspensky Petr. Name number. Secrets of numerology. Shirley B. Lawrence's book is a comprehensive study of the ancient esoteric system - numerology. To learn how to use number vibrations to…
PI, number - a mathematical constant denoting the ratio of the perimeter to the diameter of a circle. The number Pi is an irrational transcendental number, the digital representation of which is an infinite non-periodic decimal fraction - 3.141592653589793238462643 ... and so on ad infinitum.

There is no cyclicity and system in the digits after the decimal point, that is, in the decimal expansion of Pi there is any sequence of digits that you can imagine (including a very rare sequence of a million non-trivial zeros in mathematics, predicted by the German mathematician Bernhardt Riemann back in 1859).

This means that Pi, in coded form, contains all written and unwritten books, and in general any information that exists (which is why the calculations of the Japanese professor Yasumasa Kanada, who recently determined the number Pi to 12411 trillion decimal places, were right there classified - with such a volume of data it is not difficult to recreate the contents of any secret document printed before 1956, although this data is not enough to determine the location of any person, this requires at least 236734 trillion decimal places - it is assumed that such work is now being carried out in Pentagon (using quantum computers, the clock frequency of processors of which is already approaching the sound speed today).

Through the number Pi, any other constant can be defined, including the fine structure constant (alpha), the golden ratio constant (f=1.618…), not to mention the number e - that is why the number pi is found not only in geometry, but also in the theory of relativity , quantum mechanics, nuclear physics, etc. Moreover, scientists have recently found that it is through Pi that one can determine the location of elementary particles in the Table of elementary particles (previously they tried to do this through the Woody Table), and the message that in the recently deciphered human DNA, the Pi number is responsible for the DNA structure itself (enough complex, it should be noted), produced the effect of an exploding bomb!

According to Dr. Charles Cantor, under whose leadership DNA was deciphered: “It seems that we have come to unraveling some fundamental puzzle that the universe has thrown at us. The number Pi is everywhere, it controls all the processes known to us, while remaining unchanged! Who controls the Pi itself? No response yet.” In fact, Kantor is cunning, there is an answer, it’s just so incredible that scientists prefer not to make it public, fearing for their own lives (more on that later): Pi controls itself, it is reasonable! Nonsense? Do not hurry.

After all, even Fonvizin said that “in human ignorance it is very comforting to consider everything as nonsense that you don’t know.

First, conjectures about the reasonableness of numbers in general have long visited many famous mathematicians of our time. The Norwegian mathematician Niels Henrik Abel wrote to his mother in February 1829: “I have received confirmation that one of the numbers is reasonable. I spoke to him! But it scares me that I can't figure out what that number is. But maybe that's for the best. The Number warned me that I would be punished if It was revealed.” Who knows, Niels would have revealed the meaning of the number that spoke to him, but on March 6, 1829, he died.

1955, the Japanese Yutaka Taniyama puts forward the hypothesis that “every elliptic curve corresponds to a certain modular form” (as is known, Fermat's theorem was proved on the basis of this hypothesis). September 15, 1955, at the International Mathematical Symposium in Tokyo, where Taniyama announced his conjecture, to the question of a journalist: “How did you think of this?” - Taniyama replies: “I didn’t think of it, the number told me about it on the phone.”

The journalist, thinking that this was a joke, decided to “support” her: “Did it give you a phone number?” To which Taniyama replied seriously: “It seems that this number has been known to me for a long time, but now I can tell it only after three years, 51 days, 15 hours and 30 minutes.” In November 1958, Taniyama committed suicide. Three years, 51 days, 15 hours and 30 minutes is 3.1415. Coincidence? May be. But here's something even stranger. The Italian mathematician Sella Quitino also, for several years, as he himself vaguely put it, “kept in touch with one cute number.” The figure, according to Kvitino, who was already in a psychiatric hospital at that time, “promised to tell her name on her birthday.” Could Kvitino have lost his mind so much as to call the number Pi a number, or was he deliberately confusing doctors? It is not clear, but on March 14, 1827, Kvitino died.

And the most mysterious story is connected with the “great Hardy” (as you all know, this is how contemporaries called the great English mathematician Godfrey Harold Hardy), who, together with his friend John Littlewood, is famous for his work in number theory (especially in the field of Diophantine approximations) and function theory ( where friends became famous for the study of inequalities). As you know, Hardy was officially unmarried, although he repeatedly stated that he was "betrothed to the queen of our world." Fellow scientists have heard him talking to someone in his office more than once, no one has ever seen his interlocutor, although his voice - metallic and slightly raspy - has long been the talk of the town at Oxford University, where he worked in recent years . In November 1947, these conversations stop, and on December 1, 1947, Hardy is found in the city dump, with a bullet in his stomach. The version of suicide was also confirmed by a note, where Hardy's handwriting was written: "John, you stole the queen from me, I don't blame you, but I can no longer live without her."

Is this story related to pi? So far it is unclear, but isn't it curious?+

Is this story related to pi? It's not clear yet, but isn't it curious?
Generally speaking, one can dig up a lot of such stories, and, of course, not all of them are tragic.
But, let's move on to the "second": how can a number be reasonable at all? Yes, very simple. The human brain contains 100 billion neurons, the number of pi after the decimal point generally tends to infinity, in general, according to formal signs, it can be reasonable. But if you believe the work of the American physicist David Bailey and Canadian mathematicians Peter

Borwin and Simon Plofe, the sequence of decimal places in Pi is subject to chaos theory, roughly speaking, Pi is chaos in its original form. Can chaos be rational? Of course! In the same way as the vacuum, with its apparent emptiness, as you know, it is by no means empty.

Moreover, if you wish, you can represent this chaos graphically - to make sure that it can be reasonable. In 1965, the American mathematician of Polish origin Stanislav M. Ulam (it was he who came up with the key idea for the design of a thermonuclear bomb), being present at one very long and very boring (according to him) meeting, in order to somehow have fun, began to write numbers on checkered paper , included in the number Pi.

Putting 3 in the center and moving in a counterclockwise spiral, he wrote out 1, 4, 1, 5, 9, 2, 6, 5 and other numbers after the decimal point. Without any ulterior motive, he circled all the prime numbers in black circles along the way. Soon, to his surprise, the circles began to line up along the straight lines with amazing persistence - what happened was very similar to something reasonable. Especially after Ulam generated a color picture based on this drawing, using a special algorithm.

Actually, this picture, which can be compared with both the brain and the stellar nebula, can be safely called the “brain of Pi”. Approximately with the help of such a structure, this number (the only reasonable number in the universe) controls our world. But how does this control take place? As a rule, with the help of the unwritten laws of physics, chemistry, physiology, astronomy, which are controlled and corrected by a reasonable number. The above examples show that a reasonable number is also personified on purpose, communicating with scientists as a kind of superpersonality. But if so, did the number Pi come to our world, in the guise of an ordinary person?

Complex issue. Maybe it came, maybe not, there is not and cannot be a reliable method for determining this, but if this number is determined by itself in all cases, then we can assume that it came into our world as a person on the day corresponding to its value. Of course, Pi's ideal birth date is March 14, 1592 (3.141592), however, unfortunately, there are no reliable statistics for this year - it is only known that George Villiers Buckingham, the Duke of Buckingham from “ Three Musketeers." He was a great swordsman, knew a lot about horses and falconry - but was he Pi? Hardly. Duncan MacLeod, who was born on March 14, 1592, in the mountains of Scotland, could ideally claim the role of the human embodiment of the number Pi - if he were a real person.

But after all, the year (1592) can be determined according to its own, more logical chronology for Pi. If we accept this assumption, then there are many more applicants for the role of Pi.

The most obvious of them is Albert Einstein, born March 14, 1879. But 1879 is 1592 relative to 287 BC! And why exactly 287? Yes, because it was in this year that Archimedes was born, who for the first time in the world calculated the number Pi as the ratio of the circumference to the diameter and proved that it is the same for any circle!

Coincidence? But not a lot of coincidences, what do you think?

In what personality Pi is personified today, it is not clear, but in order to see the significance of this number for our world, one does not need to be a mathematician: Pi manifests itself in everything that surrounds us. And this, by the way, is very typical for any intelligent being, which, no doubt, is Pi!


To calculate any large number of signs of pi, the previous method is no longer suitable. But there are a large number of sequences that converge to Pi much faster. Let's use, for example, the Gauss formula:

p = 12 arctan 1 + 8 arctan 1 - 5 arctan 1
4 18 57 239

The proof of this formula is simple, so we will omit it.

Program source, including "long arithmetic"

The program calculates NbDigits of the first digits of Pi. The arctan calculation function is named arccot, since arctan(1/p) = arccot(p), but the calculation is carried out according to the Taylor formula for the arctangent, namely arctan(x) = x - x 3 /3 + x 5 /5 - . .. x=1/p, so arccot(x) = 1/p - 1 / p 3 / 3 + ... Calculations are recursive: the previous element of the sum is divided and gives the next one.

/* ** Pascal Sebah: September 1999 ** ** Subject: ** ** A very easy program to compute Pi with many digits. ** No optimisations, no tricks, just a basic program to learn how ** to compute in multiprecision. ** ** Formulae: ** ** Pi/4 = arctan(1/2)+arctan(1/3) (Hutton 1) ** Pi/4 = 2*arctan(1/3)+arctan(1/ 7) (Hutton 2) ** Pi/4 = 4*arctan(1/5)-arctan(1/239) (Machin) ** Pi/4 = 12*arctan(1/18)+8*arctan(1 /57)-5*arctan(1/239) (Gauss) ** ** with arctan(x) = x - x^3/3 + x^5/5 - ... ** ** The Lehmer"s measure is the sum of the inverse of the decimal ** logarithm of the pk in the arctan(1/pk). The more the measure ** is small, the more the formula is efficient. ** For example, with Machin"s formula: ** ** E = 1/log10(5)+1/log10(239) = 1.852 ** ** Data: ** ** A big real (or multiprecision real) is defined in base B as: ** X = x(0) + x(1)/B^1 + ... + x(n-1)/B^(n-1) ** where 0<=x(i)Work with double instead of long and the base B can ** be choosen as 10^8 ** => During the iterations the numbers you add are smaller ** and smaller, take this in account in the +, *, / ** => In the division of y=x/d, you may precompute 1/d and ** avoid multiplications in the loop (only with doubles) ** => MaxDiv may be increased to more than 3000 with doubles ** => . .. */#include #include #include #include long B=10000; /* Working base */ long LB=4; /* Log10(base) */ long MaxDiv=450; /* about sqrt(2^31/B) */ /* ** Set the big real x to the small integer Integer */ void SetToInteger (long n, long *x, long Integer) ( long i; for (i=1; i /* ** Is the big real x equal to zero ? */ long IsZero (long n, long *x) ( long i; for (i=0; i /* ** Addition of big reals: x += y ** Like school addition with carry management */ void Add (long n, long *x, long *y) ( long carry=0, i; for (i=n-1; i>=0; i--) ( x[i] += y[i] +carry; if (x[i] /* ** Substraction of big reals: x -= y ** Like school substraction with carry management ** x must be greater than y */ void Sub (long n, long *x, long *y) ( long i; for (i=n-1; i>=0; i--) ( x[i] -= y[i]; if (x [i]<0) { if (i) { x[i] += B; x--; } } } } /* ** Multiplication of the big real x by the integer q ** x = x*q. ** Like school multiplication with carry management */ void Mul (long n, long *x, long q) ( long carry=0, xi, i; for (i=n-1; i>=0; i--) ( xi = x[i]*q; xi += carry; if (xi>=B) ( carry = xi/B; xi -= (carry*B); ) else carry = 0; x[i] = xi; ) ) /* ** Division of the big real x by the integer d ** The result is y=x/d. ** Like school division with carry management ** d is limited to MaxDiv*MaxDiv. */ void Div (long n, long *x, long d, long *y) ( long carry=0, xi, q, i; for (i=0; i /* ** Find the arc cotangent of the integer p (that is arctan (1/p)) ** Result in the big real x (size n) ** buf1 and buf2 are two buffers of size n */ void arccot ​​(long p, long n, long *x, long *buf1, long *buf2) ( long p2=p*p, k=3, sign=0; long *uk=buf1, *vk=buf2; SetToInteger ( n, x, 0); SetToInteger(n, uk, 1); /* uk = 1/p */ Div(n, uk, p, uk); Add(n, x, uk); /* x = uk */ while (!IsZero(n, uk)) ( if (p /* Two steps for large p (see division) */ Div(n, uk, p, uk); ) /* uk = u(k-1)/(p^2) */ Div (n, uk, k, vk); /* vk = uk/k */ if (sign) Add (n, x, vk); /* x = x+vk */ else Sub(n, x, vk); /* x = x-vk */ k+=2; sign = 1-sign; ) ) /* ** Print the big real x */ void Print (long n, long *x) ( long i; printf ("%d.", x); for (i=1; i /* ** Computation of the constant Pi with arctan relations */ void main () ( clock_t endclock, startclock; long NbDigits=10000, NbArctan; long p, m; long size=1+NbDigits/LB, i; long *Pi = (long *)malloc(size*sizeof(long)) ; long *arctan = (long *)malloc(size*sizeof(long)); long *buffer1 = (long *)malloc(size*sizeof(long)); long *buffer2 = (long *)malloc(size*sizeof (long)); startclock = clock(); /* ** Formula used: ** ** Pi/4 = 12*arctan(1/18)+8*arctan(1/57)-5*arctan(1/239) (Gauss) */ NbArctan = 3; m = 12; m = 8; m = -5; p=18; p=57; p=239; SetToInteger(size, Pi, 0); /* ** Computation of Pi/4 = Sum(i) *arctan(1/p[i])] */ for (i=0; i 0) Add(size, Pi, arctan); else Sub(size, Pi, arctan); ) Mul(size, Pi, 4); endclock = clock(); Print(size, Pi); /* Print out of Pi */ printf ("Computation time is: %9.2f seconds\n", (float)(endclock-startclock)/(float)CLOCKS_PER_SEC); free(Pi); free(arctan); free(buffer1); free(buffer2); )

Of course, these are not the most efficient ways to calculate pi. There are many more formulas. For example, Chudnovsky's formula, variations of which are used in Maple. However, in normal programming practice, the Gauss formula is enough, so these methods will not be described in the article. It is unlikely that anyone wants to calculate billions of digits of pi, for which a complex formula gives a large increase in speed.