-
Notifications
You must be signed in to change notification settings - Fork 1
Big Functions
SimpleArt edited this page Oct 30, 2021
·
3 revisions
It may be necessary for some usage to define mathematical operations, such as exponentiation, over intervals beyond their usual domain. This is especially the case when one desires evaluations at infinity or near singularities. We define several such functions below from test.py.
from math import exp, inf
def bigexp(x: float) -> float:
"""Implements big exponentiation by using inf if it overflows."""
try:
return exp(x)
except OverflowError:
return inffrom math import inf
from pyroot import sign
def bigpow(x: float, y: float) -> float:
"""
Implements pow(x, y) with handling of overflow as
using inf and some sign manipulation.
If x == 0 and y == 0, then return 1.0.
If y < 0, then return 1 / bigpow(x, -y), or inf in the case of division by 0.
Otherwise y > 0, and the result is pow(x, y) as expected, using inf appropriately.
If x < 0 and y == int(y), then the sign is sign(x) ** y.
Otherwise the sign of x is used.
"""
# Attempt to use the built-in pow.
try:
result = pow(x, y)
# If division by 0 occurs, return inf.
except ZeroDivisionError:
return inf
# If overflow occurs, return inf with an appropriate sign.
# If sign(x) ** y would be complex, just use sign(x) instead.
except OverflowError:
return sign(x) ** y * inf if y == int(y) else sign(x) * inf
# Check for complex values.
else:
return sign(x) * pow(abs(x), y) if isinstance(result, complex) else resultNote the conventions chosen here are 1/0.0 == inf and (-inf)**y == inf if y is a positive non-integer.
from math import inf, log, nan
def biglog(x: float) -> float:
"""Implements big logarithm with log(0) == -inf and log(x<0) == nan."""
return -inf if x == 0 else nan if x < 0 else log(x)from math import nan, sqrt
def bigsqrt(x: float) -> float:
"""Implements big square root with sqrt(x<0) == nan."""
return nan if x < 0 else sqrt(x)from math import isinf, sin
def bigsin(x: float) -> float:
"""Uses sin(inf) = 0 since sin(inf) usually doesn't actually matter."""
return 0 if isinf(x) else sin(x)from math import cos, isinf
def bigcos(x: float) -> float:
"""Uses cos(inf) = 0 since cos(inf) usually doesn't actually matter."""
return 0 if isinf(x) else cos(x)