Ejemplo n.º 1
0
 def evaluate(self, x):
     """Evaluate itself with varaible x"""
     index = final = ComplexDecimal(0)
     for i in self.terms:
         final += i * x**index
         index += ComplexDecimal(1)
     return final
Ejemplo n.º 2
0
def factors(a):
    if a > ComplexDecimal(1000000):
        return []
    f = []
    for i in range(1, int(math.ceil(math.sqrt(a)))):
        if a % ComplexDecimal(i) == ComplexDecimal(0):
            f.append(ComplexDecimal(i))
            f.append(a / ComplexDecimal(i))
    return f
Ejemplo n.º 3
0
def double_fact(n):
    if n.imaginary != 0:
        raise ArithmeticError("You cannot have imaginary factorial.")
    if n < ComplexDecimal(0):
        raise ArithmeticError("You cannot have negative factorial.")
    if n < ComplexDecimal(2): return ComplexDecimal(1)

    returned = ComplexDecimal(1)
    for i in range(int(n), 1, -2):
        returned *= ComplexDecimal(i)
    return returned
Ejemplo n.º 4
0
    def get_roots(self):
        if self.degree == 0: return [self.terms[0]]  #Constant
        elif self.degree == 1:  #Linear equation
            return [-self.terms[0] / self.terms[1]]
        elif self.degree == 2:  #Quadratic
            a, b, c = self.terms[2], self.terms[1], self.terms[0]
            dis = b * b - ComplexDecimal(4) * a * c
            root1 = (-b + dis.sqrt()) / ComplexDecimal(2) / a
            root2 = (-b - dis.sqrt()) / ComplexDecimal(2) / a
            return [root1, root2]

        r = ComplexDecimal(5)  #Bad inital guess, but who's going to use this?
        for i in range(0, 20):
            r = r - self.evaluate(r) / self.derv().evaluate(r)
        return [r]
Ejemplo n.º 5
0
    def __init__(self, *terms):  #Array of terms or a string to phrase
        """Self.terms is an array
        index 0 is the constant, index 1 is the term with degree 1, etc...
        So 3x^2 + 2x + 1 would be [1,2,3]
        However when defining define in right to left order
        for example Polynomial(1,2,3) would be x^2 + 2x + 3, not 3x^2 + 2x + 1
        
        Functions:
            Add, subtract, divide, multiply, powers, etc...
            Factor
            GCD, GCF
            Intergal

            Pretty printing :D"""

        self.terms = []
        if type(terms[0]) == list: terms = terms[0]
        for i in terms:
            if type(i) != ComplexDecimal: self.terms.append(ComplexDecimal(i))
            else: self.terms.append(i)
        self.terms.reverse()

        #Define some things
        self.degree = len(self.terms) - 1
        self.length = len(self.terms)
        self.names = [self.get_name_degree(), self.get_name_terms()]

        self.roots = self.get_roots()

        #Refine some function names
        self.eval = self.evaluate
Ejemplo n.º 6
0
 def derv(self):  #Derviative of self :D
     new_terms = []
     index = 0
     for i in self.terms:
         if index == 0: pass
         else:
             new_terms.append(i * ComplexDecimal(index))
         index += 1
     new_terms.reverse()
     return Polynomial(new_terms)
Ejemplo n.º 7
0
def computeEquation(m, opt={}):
    options = {}
    options["prec"] = opt.get("prec") or 28  #DONE
    options["Emin"] = opt.get("Emin") or -999999999  #DONE
    options["Emax"] = opt.get("Emax") or 999999999  #DONE
    options["easter_egg"] = opt.get("easter_egg") or True  #DONE
    options["safe"] = opt.get("safe") or False  #DONE
    options["trig"] = opt.get("trig") or "RAD"  #DONE
    constant = opt.get("constants") or constants.constants

    #Remove any extra white space
    m = m.lstrip().rstrip()
    decimal.getcontext().Emax = options["Emax"]
    decimal.getcontext().Emin = options["Emin"]
    decimal.getcontext().prec = options["prec"]

    if options["easter_egg"] and m != "":
        #Answer the meaning of life
        m1 = m.lower()
        if "answer to the ultimate question of life the universe and everything".startswith(
                m1.strip(",")):
            return ComplexDecimal("42")
        elif "answer to life the universe and everything".startswith(
                m1.strip(",")):
            return ComplexDecimal("42")
        elif "the meaning of life the universe and everything".startswith(
                m1.strip(",")):
            return ComplexDecimal("42")
        #Blue moon
        elif m1 == "once in a blue moon":
            return ComplexDecimal("1.16699016") * ComplexDecimal(
                "10")**ComplexDecimal("-8")
        #Misc
        elif m1 == "the number of horns on a unicorn":
            return ComplexDecimal("1")
        elif m1 in [
                "what is the loneliest number", "the loneliest number",
                "loneliest number"
        ]:
            return ComplexDecimal("1")
        elif m1 == "my ass":
            return ComplexDecimal("Inf")

    #Fix e notation
    p = re.compile('([:]?\d*\.\d+|\d+)e([-+]?)([-+]?\d*\.\d+|\d+)')
    subst = "(\\1 * 10**\\2\\3)"
    m = re.sub(p, subst, m)
    p = re.compile('([:]?\d*\.\d+|\d+)E([-+]?)([-+]?\d*\.\d+|\d+)')
    subst = "(\\1 * 10**\\2\\3)"
    m = re.sub(p, subst, m)

    #Replace the constants
    #a) [number]pi : for example
    #b) (something)pi : for example
    #c) varaibles bythemselves, ie pi+pi
    for c in constant:
        m = m.replace("){}".format(c), ") * {}".format(constant[c]))
        p = re.compile('([:]?\d*\.\d+|\d+){}'.format(c))
        subst = "\\1 * " + constant[c]
        m = re.sub(p, subst, m)
        m = re.sub('\\b{}\\b'.format(c), constant[c], m)

    #Delete unsafe variables
    if options["safe"]:
        for i in safe.unsafe:
            m = m.replace(i, "")

    #Fix powers
    m = m.replace("^", "**")

    #Fix logical operators
    m = m.replace("||", " or ")
    m = m.replace("&&", " and ")

    #Change functions into proper forms
    #----------------------------------------------------------------------------------
    #Change double factorials, ie 5!! -> double_fact(5)
    p = re.compile('(-?\d+)!!')
    subst = "double_fact(\\1)"
    m = re.sub(p, subst, m)
    p = re.compile('\(([^)\n]*?)\)!!')
    m = re.sub(p, "double_fact(\\1)", m)

    #Change factorials, ie 5! -> fact(5)
    p = re.compile('(-?\d+)!')
    subst = "factorial(\\1)"
    m = re.sub(p, subst, m)
    p = re.compile('\(([^)\n]*?)\)!')
    m = re.sub(p, "factorial(\\1)", m)

    #Change percents, ie 5% -> 0.05
    p = re.compile('(-?\d+)%')
    subst = "(\\1 / 100)"
    m = re.sub(p, subst, m)
    p = re.compile('\(([^)\n]*?)\)%')
    m = re.sub(p, "(\\1 / 100)", m)

    p = re.compile('(-?\d+)ppm')
    subst = "(\\1 / 1000000)"
    m = re.sub(p, subst, m)
    p = re.compile('\(([^)\n]*?)\)ppm')
    m = re.sub(p, "(\\1 / 1000000)", m)

    p = re.compile('(-?\d+)ppb')
    subst = "(\\1 / 1000000000)"
    m = re.sub(p, subst, m)
    p = re.compile('\(([^)\n]*?)\)ppb')
    m = re.sub(p, "(\\1 / 1000000000)", m)

    p = re.compile('(-?\d+)ppt')
    subst = "(\\1 / 1000000000000)"
    m = re.sub(p, subst, m)
    p = re.compile('\(([^)\n]*?)\)ppt')
    m = re.sub(p, "(\\1 / 1000000000000)", m)

    #Change absolute value
    m = re.sub("\|(.*?)\|", "abs(\\1)", m)

    #Fix dates
    m = re.sub("Date\((.*?)\)", 'Date("\\1")', m)

    #Change choice things like nPr and nCr
    #Regex: (Number)P(Number) = npr(a,b)
    m = re.sub("(-?\d+)P(-?\d+)", "nPr(\\1,\\2)", m)
    m = re.sub("(-?\d+)C(-?\d+)", "nCr(\\1,\\2)", m)

    #Fix trig modes
    if options["trig"] == "DEG":
        m = " " + m
        m = re.sub("asin\((.*?)\)", "deg(asin(\\1))", m)
        m = re.sub("acos\((.*?)\)", "deg(acos(\\1))", m)
        m = re.sub("atan\((.*?)\)", "deg(atan(\\1))", m)
        m = re.sub("[^a]sin\((.*?)\)", "sin(rad(\\1))", m)
        m = re.sub("[^a]cos\((.*?)\)", "cos(rad(\\1))", m)
        m = re.sub("[^a]tan\((.*?)\)", "tan(rad(\\1))", m)

        m = re.sub("asinh\((.*?)\)", "deg(asinh(\\1))", m)
        m = re.sub("acosh\((.*?)\)", "deg(acosh(\\1))", m)
        m = re.sub("atanh\((.*?)\)", "deg(atanh(\\1))", m)
        m = re.sub("[^a]sinh\((.*?)\)", "sinh(rad(\\1))", m)
        m = re.sub("[^a]cosh\((.*?)\)", "cosh(rad(\\1))", m)
        m = re.sub("[^a]tanh\((.*?)\)", "tanh(rad(\\1))", m)
    elif options["trig"] == "GRAD":
        m = " " + m
        m = re.sub("asin\((.*?)\)", "rad_to_grad(asin(\\1))", m)
        m = re.sub("acos\((.*?)\)", "rad_to_grad(acos(\\1))", m)
        m = re.sub("atan\((.*?)\)", "rad_to_grad(atan(\\1))", m)
        m = re.sub("[^a]sin\((.*?)\)", "sin(grad_to_rad(\\1))", m)
        m = re.sub("[^a]cos\((.*?)\)", "cos(grad_to_rad(\\1))", m)
        m = re.sub("[^a]tan\((.*?)\)", "tan(grad_to_rad(\\1))", m)

        m = re.sub("asinh\((.*?)\)", "rad_to_grad(asinh(\\1))", m)
        m = re.sub("acosh\((.*?)\)", "rad_to_grad(acosh(\\1))", m)
        m = re.sub("atanh\((.*?)\)", "rad_to_grad(atanh(\\1))", m)
        m = re.sub("[^a]sinh\((.*?)\)", "sinh(grad_to_rad(\\1))", m)
        m = re.sub("[^a]cosh\((.*?)\)", "cosh(grad_to_rad(\\1))", m)
        m = re.sub("[^a]tanh\((.*?)\)", "tanh(grad_to_rad(\\1))", m)

    #Converts all remaining numbers into numbers
    p = re.compile('([:]?\d*\.\d+|\d+)')
    subst = "ComplexDecimal('\\1')"
    m = re.sub(p, subst, m)

    #Fix i
    m = m.replace(")i", ") * {}".format("ComplexDecimal(0,1)"))
    p = re.compile('([:]?\d*\.\d+|\d+)i')
    subst = "\\1 * " + "ComplexDecimal(0,1)"
    m = re.sub(p, subst, m)
    m = re.sub('\\b{}\\b'.format("i"), "ComplexDecimal(0,1)", m)

    result = eval(m, {"__builtins__": None}, safe.safe_dict)
    return result
Ejemplo n.º 8
0
 def __sub__(self, other):
     return ComplexDecimal(
         abs((other.to_datetime() - self.to_datetime()).total_seconds()))
Ejemplo n.º 9
0
def isPrime(n):
    if n > ComplexDecimal(1000000): return None
    return n.isPrime()
Ejemplo n.º 10
0
def gcf(a, b):
    while b != ComplexDecimal(0):
        a, b = b, a % b
    return a
Ejemplo n.º 11
0
def uniform(a, b=ComplexDecimal(0)):
    if b < a:  #Swap if b > a
        a, b = b, a
    a = int(a)
    b = int(b)
    return ComplexDecimal(random.uniform(a, b))
Ejemplo n.º 12
0
def rand(a, b=ComplexDecimal(0)):
    if b < a:  #Swap if b > a
        a, b = b, a
    a = int(a)
    b = int(b)
    return ComplexDecimal(random.randint(a, b))
Ejemplo n.º 13
0
def rad_to_grad(n):
    return n * ComplexDecimal(200) / ComplexDecimal(constants.constants["pi"])
Ejemplo n.º 14
0
def degree(n):
    return n * ComplexDecimal(180) / ComplexDecimal(constants.constants["pi"])
Ejemplo n.º 15
0
def radian(n):
    return n * ComplexDecimal(constants.constants["pi"]) / ComplexDecimal(180)