Exemple #1
0
def compute_pi(nodecimals=0):
    """
    Obtain the first nodecimals number of decimals
    of pi=3.1415... by aproximation using euler's formula:
    pi = infinity_sum(  (factorial(n)**2)*(2**(n+1)) / (factorial(2*n +1)) )

    http://mathworld.wolfram.com/PiFormulas.html
    """
    if not isinstance(nodecimals, int):
        raise Exception('The parameter nodecimals must be an integer.')
    if nodecimals < 0:
        raise Exception('The parameter nodecimals must be positive.')

    if nodecimals == 0:
        return LongDecimal(ciphers=[3])

    nodecimals += 2  # extra precision to avoid rounding up errors

    ciphers = [0] * (nodecimals + 1)

    pi = LongDecimal(ciphers=ciphers, negative=False)

    term = 0
    euler_term = LongDecimalEuler(term=term, nodecimals=nodecimals)

    while not euler_term.iszero():
        pi = pi + euler_term

        term += 1

        euler_term = LongDecimalEuler(term=term, nodecimals=nodecimals)
    pi.setprecision(nodecimals - 2)
    return pi
    def test_setprecision_with_same_precision(self):
        """
            Test that setprecision with the same precision
            doesn't change the Long Decimal.
            """
        ciphers = [1, 2, 3, 4, 5]
        ld = LongDecimal(ciphers=ciphers)

        new_precision = len(ciphers) - 1

        ld.setprecision(new_precision=new_precision)

        self.assertEqual(len(ld), len(ciphers))
        self.assertEqual(ld._ciphers, ciphers)
    def test_setprecision_with_more_precision(self):
        """
            Test setprecision method
            when new_precision > current_precision.
            """
        ciphers = [1, 2, 3, 4, 5]
        ld = LongDecimal(ciphers=ciphers)

        new_precision = 5

        ld.setprecision(new_precision=new_precision)

        self.assertEqual(len(ld), new_precision + 1)
        self.assertEqual(ld._ciphers,
                         ciphers + [0] * (new_precision - len(ciphers) + 1))
    def test_setprecision_with_less_precision(self):
        """
            Test setprecision method
            when new_precision < current_precision.
            """
        ciphers = [1, 2, 3, 4, 5]
        ld = LongDecimal(ciphers=ciphers)

        self.assertEqual(len(ld), len(ciphers))
        new_precision = 2

        ld.setprecision(new_precision=new_precision)

        self.assertEqual(len(ld), new_precision + 1)
        self.assertEqual(ld._ciphers, ciphers[:new_precision + 1])