Some useful math parsing functions I wrote a while ago

I :heart: +-*/

Here are some nice functions which let you perform tasks with non-integers with infinite precision.

def sub_frac(num1, den1, num2, den2):
    """Subtracts two fractions."""
    common_den = math.lcm(den1, den2)
    num1 *= common_den/den1
    num2 *= common_den/den2
    num = num1 - num2
    return num, common_den

def simplify(num, den):
    neg = -1 if num * den < 0 else 1
    if neg:
        num, den = abs(num), abs(den)
    factor = gcd(num, den)
    return (num//factor *neg, den//factor)

def factor_sqrt(num, factors=[]):
    #print(num, factors)
    for i in range(2, math.floor(math.sqrt(num))+2): #theoretically we only need 1 but lets give it 2 just incase.
        if (i%2 == 0 and i>2) or (i%3 == 0 and i>3):
        if num % (i**2) == 0:
            factors = factors + [i]
            #print(num, i, num//(i**2), factors)
            return factor_sqrt(num//(i**2), factors)
    return, num

def frac(num, den):
    num = int(num)
    den = int(den)
    if num < 0 and den < 0:
        num = abs(num)
        den = abs(den)
    if num == 1 and den == 0:
        num = "[INF]"
        den = 1
    if den != 1:
        return f"{num}/{den}"
    return f"{num}"

You can find more in my parallel line distance calculator.


Do we need to import math first? It seems like we do.

1 Like

Can’t you just use fractions?

1 Like

nah, the point is that I don’t want to use fractions (but make one myself).

1 Like