Java Pi calculator getting stuck

I would rather use this code for the PI approach from the rectangles approximates: int rectangleCount = 100; double width = 0.0; double pi = 0.0; double height = 0.0; double radius = 1.0; for (int i = 1; i <= rectangleCount; i++) { width = (double)i / rectangleCount; height = Math.sqrt(radius – width*width); pi … Read more

Print pi to a number of decimal places

The proposed solutions using np.pi, math.pi, etc only only work to double precision (~14 digits), to get higher precision you need to use multi-precision, for example the mpmath package >>> from mpmath import mp >>> mp.dps = 20 # set number of digits >>> print(mp.pi) 3.1415926535897932385 Using np.pi gives the wrong result >>> format(np.pi, ‘.20f’) … Read more

Python pi calculation?

It seems you are losing precision in this line: pi = pi * Decimal(12)/Decimal(640320**(1.5)) Try using: pi = pi * Decimal(12)/Decimal(640320**Decimal(1.5)) This happens because even though Python can handle arbitrary scale integers, it doesn’t do so well with floats. Bonus A single line implementation using another algorithm (the BBP formula): from decimal import Decimal, getcontext … Read more

Why do I get “OverflowError: (34, ‘Result too large’)” or “OverflowError: (34, ‘Numerical result out of range’)” from floating-point exponentiation?

Python floats are neither arbitary precision nor of unlimited size. When k = 349, 16.**k is much too large – that’s almost 2^1400. Fortunately, the decimal library allows arbitrary precision and can handle the size: import decimal decimal.getcontext().prec = 100 def pi(): pi = decimal.Decimal(0) for k in range(350): pi += (decimal.Decimal(4)/(decimal.Decimal(8)*decimal.Decimal(k+1))…)

How to printf long long

%lld is the standard C99 way, but that doesn’t work on the compiler that I’m using (mingw32-gcc v4.6.0). The way to do it on this compiler is: %I64d So try this: if(e%n==0)printf(“%15I64d -> %1.16I64d\n”,e, 4*pi); and scanf(“%I64d”, &n); The only way I know of for doing this in a completely portable way is to use … Read more

Gauss-Legendre Algorithm in python

You forgot parentheses around 4*t: pi = (a+b)**2 / (4*t) You can use decimal to perform calculation with higher precision. #!/usr/bin/env python from __future__ import with_statement import decimal def pi_gauss_legendre(): D = decimal.Decimal with decimal.localcontext() as ctx: ctx.prec += 2 a, b, t, p = 1, 1/D(2).sqrt(), 1/D(4), 1 pi = None while 1: an … Read more

1000 digits of pi in Python

If you don’t want to implement your own algorithm, you can use mpmath. try: # import version included with old SymPy from sympy.mpmath import mp except ImportError: # import newer version from mpmath import mp mp.dps = 1000 # set number of digits print(mp.pi) # print pi to a thousand places Reference Update: Code supports … Read more