Find Roots Of A Parabola

redyugi 0 Tallied Votes 424 Views Share

This is used for finding the roots of a parabola. The parabola must have a number in front of x2 (x squared), a number in front of the single x, and a following number, or you can have a perfect square parabola. (in the form "number x2 - number")
This function returns a string.

This code snippet comes with 3 functions.
Find_Roots(parabola) - finds the roots of a parabola
Find_Multi(mult, num) - finds what numbers add together to get "num" and multiply together to get "mult"
Is_SquareRoot(number) - returns True if number is a perfect square

import re, string

def Find_Roots(parabola):
    """Finds the roots of a parabola"""
    ro = re.compile("[1-9]*x2[-, +][1-9]*x[+, -][1-9]*") # Compiles expressions to check if argument is a parabola
    rw = re.compile("[1-9]*x2-[1-9]*")
    if ro.match(parabola):
        list1 = string.split(parabola, "+") 
        w = string.join(list1, "-")
        list2 = string.split(w, "-", 2)
        square = int(list2[0].replace("x2", ""))
        x = int(list2[1].replace("x", ""))
        num = int(list2[2])
        if square == 1:
            roots = Find_Multi(num, x)
            if abs(roots[0]) == roots[0]:
                roots[0] = string.join(["+", str(roots[0])])
            else:
                roots[0] = str(roots[0]).replace("-", "- ")
            if abs(roots[1]) == roots[1]:
                roots[1] = string.join(["+", str(roots[1])])
            else:
                roots[1] = str(roots[1]).replace("-", "- ")
            x = "(x %s)(x %s)\n(x=%s)(x=%s)" % (roots[0], roots[1], -(int(roots[0])), -(int(roots[1])))
            return x
        else:
            num *= square
            place = [square, square]
            roots = Find_Multi(num, x)
            r = []
            if roots[0]/square == roots[0]/float(square):
                roots[0] /= square
                place[0] = ""
                r.append(roots[0])
            else:
                if (-(roots[0]))/square == (-(roots[0]))/float(square):
                    r.append((-(roots[0]))/square)
                else:
                    r.append("%s/%s" % (-(roots[0]), square))
            if roots[1]/square == roots[1]/float(square):
                roots[1] /= square
                place[1] = ""
                r.append(roots[1])
            else:
                if (-(roots[1]))/square == (-(roots[1]))/float(square):
                    r.append((-(roots[1]))/square)
                else:
                    r.append("%s/%s" % (-(roots[0]), square))
            if abs(roots[0]) == roots[0]:
                roots[0] = string.join(["+", str(roots[0])])
            else:
                roots[0] = str(roots[0]).replace("-", "- ")
            if abs(roots[1]) == roots[1]:
                roots[1] = string.join(["+", str(roots[1])])
            else:
                roots[1] = str(roots[1]).replace("-", "- ")
            x = "(%sx %s)(%sx %s)\n(x=%s)(x=%s)" % (place[0], roots[0], place[1], roots[1], r[0],r[1])
            return x
    elif rw.match(parabola):
        list1 = string.split(parabola, "-")
        square = int((str(list1[0]).replace("x2", "")))
        num = int(list1[1])
        if square > 1:
            if Is_SquareRoot(square) and Is_SquareRoot(num):
                roots = [int(math.sqrt(num)), int(math.sqrt(num))]
                front = [int(math.sqrt(square)), int(math.sqrt(square))]
                x = "(%sx - %s)(%sx + %s)" % (front[0], roots[0], front[1], roots[0])
                y = []
                if (-(roots[0]))/front[0] == (-(roots[0]))/float(front[0]):
                    y.append("(x=%s)" % ((-(roots[0]))/front[0]))
                else:
                    y.append("(x=%s/%s)" % (-(roots[0]), front[0]))
                if (-(roots[1]))/front[1] == (-(roots[0]))/float(front[1]):
                    y.append("(x=%s)" %((-(roots[0]))/front[1]))
                else:
                    y.append("(x=%s/%s)" % (-(roots[0]), front[1]))
                return string.join([x, "\n", string.join(y)], "")
        else:
            if Is_SquareRoot(num):
                roots = [int(math.sqrt(num)), int(math.sqrt(num))]
                x = "(x - %s)(x + %s)" % (roots[0], roots[1])
                y = "(x = %s)(x = %s)" % (-roots[0], -roots[1])
                return string.join([x, "\n", y], "")
def Find_Multi(mult, add):
    if type(mult) ==  int:
        list1=[]
        if -mult > mult:
            for i in range(mult, -(mult+1)):
                if i:
                    x = mult/i
                    y = mult/float(i)
                    if x == y:
                        list1.append(i)
        else:
            for i in range(-mult, mult+1):
                if= i:
                    x = mult/i
                    y = mult/float(i)
                    if x == y:
                        list1.append(i)
    x = list1
    for i in x:
        for w in x:
            if i+w == add and i*w == mult:
                num = [w, i]
                break
    return num

def Is_SquareRoot(number):
    x = math.sqrt(number)
    y = round(x)
    if x == y:
        return True
    else:
        return False

if __name__ == "__main__":
    print Find_Roots("1x2-9")
jey1234 4 Newbie Poster

I only started learning python last week and since I am in Grade 11, I thought it would be a good idea to program something that gives the roots and vertex of any given parabola in the general form. But my code looks a lot simpler and shorter. Why? Btw I couldn't compile your code. It gave errors. O: Confused. Thanks.

My code:

# Quadratic Solver
# 10/09/10

from math import exp, sqrt

print "Quadratic Solver 1.0"
print "10/09/10"


print \
"""

                               Quadratic Solver

                                  ax^2+bx+c
                                         __________
                            x= -b (+-) \/b^2 - 4ac
                               _____________________
                                         2a


"""
a = raw_input("a: ")
a = float(a)
b = raw_input("b: ")
b = float(b)
c = raw_input("c: ")
c = float(c)

bsquared = b**2
four_ac = -4 * a * c
delta = bsquared + four_ac

if delta < 0:
    print "\nNo Zeros"
else:
    roots = sqrt(delta)

    top_pos = -1 * b + roots
    top_neg = -1 * b - roots

    bottom = 2 * a
    root_pos = top_pos / bottom
    root_neg = top_neg / bottom

    print "\nRoot 1: ", root_pos
    print "Root 2: ", root_neg

vertex_top = -1 *b
bottom = 2 * a
h = vertex_top / bottom

vertex_squared = h**2
vertex_1 = a * vertex_squared
vertex_2 = b * h
k = vertex_1 + vertex_2 + c

print "\nVertex: (", h, ",", k, ")"

raw_input("\nPlease Press Enter to Exit")
commented: nice code +4
redyugi 5 Junior Poster in Training

It would give errors. This was back when I was in Trig/Algbra II and was just learning Python.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.