예제 #1
0
 def test_inverse(self):
     """Test inverse function."""
     self.assertEqual(common.inverse(5), 1 / 5)
     self.assertEqual(common.inverse(-5), -1 / 5)
     self.assertEqual(common.inverse(-1 / 5), -5)
     # Test divisor of 0.
     with self.assertRaises(the_exception.InputError):
         common.inverse(0)
예제 #2
0
def tanh(argument: float) -> float:
    """Returns an approximation of the value of tanh('argument').

    Args:
        argument (float): Input to hyperbolic tan function

    Returns:
        float: Approximation of the value of tanh('argument')
    """
    e = exp.pow_e(argument)
    return (e - common.inverse(e)) / (e + common.inverse(e))
예제 #3
0
def pow_int(base: float, exponent: int) -> float:
    """Returns value of 'base' to the power of 'exponent' using exponentiation by squaring where the latter is an integer.

    Args:
        base (float): Base of power to be returned
        exponent (int): Exponent of power to be returned

    Returns:
        float: Value of 'base' to the power of 'exponent'

    Raises:
        InputError: If 'exponent' is not an integer
    """
    # Ensure that exponent is an integer.
    if not isinstance(exponent, int):
        raise exceptions.InputError(
            exponent,
            "Exponentiation by squaring does not work with non-integer exponents."
        )

    # If exponent is negative, use the property x^y = (1/x)^-y.
    if common.is_negative(exponent):
        base = common.inverse(base)
        exponent *= -1

    # Iterate over bits in exponent
    result = 1
    while common.is_positive(exponent):
        # If exponent is odd, we can use the fact that x^y = x(x^2)^((n-1)/2)
        if common.is_odd(exponent):
            result *= base
            # Normally, we'd subtract 1 from y here but we don't actually need to since it will be lost in the coming bit-shift.
        # Now that y is even, we can use the fact that x^y = (x^2)^(n/2) when y is even
        base *= base
        exponent >>= 1
    return result