Download code

Jump to: navigation, search

Back to Pi_with_Machin's_formula_(Erlang)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

machin.erl

 1 % The authors of this work have released all rights to it and placed it
 2 % in the public domain under the Creative Commons CC0 1.0 waiver
 3 % (http://creativecommons.org/publicdomain/zero/1.0/).
 4 % 
 5 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 % EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 % MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 % IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 % CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 % TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 % SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 % 
13 % Retrieved from: http://en.literateprograms.org/Pi_with_Machin's_formula_(Erlang)?oldid=16330
14 
15 -module(machin).
16 -export([pi/1]).
17 arccot(X, Unity) ->
18     Start = Unity div X,
19     arccot(X, Unity, 0, Start, 1, 1).
20 
21 arccot(_X, _Unity, Sum, XPower, N, _Sign) when XPower div N =:= 0 ->
22     Sum;
23 arccot(X, Unity, Sum, XPower, N, Sign) ->
24     Term = XPower div N,
25     arccot(X, Unity, Sum + Sign*Term, XPower div (X*X), N+2, -Sign).
26 
27 pi(Digits) ->
28     Unity = pow(10, Digits+10),
29     Pi = 4 * (4 * arccot(5, Unity) - arccot(239, Unity)),
30     Pi div pow(10,10).
31 pow(Base, Exponent) when Exponent < 0 ->
32   pow(1 / Base, -Exponent);
33 
34 pow(Base, Exponent) when is_integer(Exponent) ->
35   pow(Exponent, 1, Base).
36 
37 pow(0, Product, _Modifier) ->
38   Product;
39 
40 pow(Exponent, Product, Modifier) when Exponent rem 2 =:= 1 ->
41   pow(Exponent div 2, Product * Modifier, Modifier * Modifier);
42 
43 pow(Exponent, Product, Modifier) ->
44   pow(Exponent div 2, Product, Modifier * Modifier).


hijacker
hijacker
hijacker
hijacker