Created
November 30, 2021 04:56
-
-
Save Kenny2github/9e53d7d42a131ccea5ca999ab5346fc4 to your computer and use it in GitHub Desktop.
A Python implementation of the exponential function generalized to anything that supports Taylor series operations.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def exp(z, zero=None, one=None, equality=lambda a, b: a == b): | |
"""Raise e to the power of z. | |
z need only support the following: | |
- Addition with its own type | |
- Multiplication with its own type | |
- Multiplication with float | |
Provide ``zero`` if z - z != the zero of its type. | |
This function will probably not produce correct results | |
if this is the case, but it is provided for completeness. | |
If ``one`` is not provided, z must also support | |
division with its own type (to construct the identity | |
value of its type). | |
Example: for numpy matrices, one should be the | |
identity matrix of the correct size. | |
``equality`` is called on the values between two successive | |
iterations to determine when to stop iterating, and is | |
a regular == check by default. | |
Example: for numpy matrices, equality should be | |
lambda a, b: (a == b).all() | |
""" | |
i = current_factorial = 0 | |
# construct the zero and one values of the z type | |
if zero is None: | |
# z may not support subtraction or negation, | |
# so multiply it by -1; since it may not support | |
# multiplication with integers, multiply by -1.0 | |
zero = z + (z * -1.0) | |
if one is None: | |
one = z / z | |
result = zero | |
z_tothe_n = one | |
# initial value arbitrarily different from result | |
last_result = one | |
while not equality(last_result, result): | |
last_result = result | |
# z^n / n! | |
# division guarantees a float, the multiplication of which | |
# must be supported by z and its ilk | |
result = result + z_tothe_n * (1 / (current_factorial or 1)) | |
# compute next z^n | |
z_tothe_n = z_tothe_n * z | |
# compute next n! | |
i += 1 | |
# or 1 handles 0! = 1 | |
current_factorial = (current_factorial * i) or 1 | |
return last_result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment