def find_root_newtonRaphson(function_string, x):
    """
    :param function_string: the equation which we want to get the root
    :param x: the initial guess of the root
    :return: the root of the equation and NONE if the equation diverged or the number of iterations is above MAX_ITERATIONS
    """
    formatter = Formatter()
    formatter.add_entry("Xi", "f(Xi)", "F'(Xi)", "Xi+1")
    fun = Func(function_string)
    found = False
    for i in range(0, constants.MAX_ITERATIONS):
        fx = (fun.get_value_at(x))
        gx = (fun.get_derivative_value_at(x))  # gx is d/dx (fx)
        formatter.add_entry(x, fx, gx, x - fx / gx)
        # print(x , fx , gx , x-x-fx/gx,sep = "<><><><><>")
        r = (fx / gx)
        if abs(r) < constants.EPS:
            found = True
            break
        x = x - r

    if not found:
        print(
            "The method diverged .Sorry but we can not solve this equation using newton "
        )
        return None
    else:
        formatter.display_steps()
        return x
def find_root_bisection(function_string, l, r):
    formatter = Formatter()
    formatter.add_entry("l", "r", "f(l)", "f(r)", "mid", "f(mid)")
    fun = Func(function_string)
    fl = fun.get_value_at(l)
    fr = fun.get_value_at(r)
    if fl * fr > 0:
        print(
            "Sorry but Bisection method can not solve an equation with the given interval"
        )
        return None
#    print("eps ", constants.EPS)
    itr = 0
    while abs(r - l) > constants.EPS and itr < constants.MAX_ITERATIONS:
        m = l + (r - l) / 2
        fm = fun.get_value_at(m)
        #       print(l, r, fl, fr, m, fm, sep=' <><> ')
        formatter.add_entry(l, r, fl, fr, m, fm)
        if fm * fl > 0:
            l = m
        else:
            r = m
    if abs(r - l) > constants.EPS:
        print(
            "Bisection method has iterated more than the maximum number of iterations "
        )
    formatter.display_steps()
    return (r + l) / 2
Example #3
0
def draw(function_string, left, right):
    seg = (right - left) / constants.PLOT_POINTS
    fun = Func(function_string)
    xs = list()
    ys = list()
    while left < right:
        #print(left)
        xs.append(left)
        ys.append(fun.get_value_at(left))
        left += seg
    draw_from_lists(xs, ys)
Example #4
0
def find_root_falsePosition(function_string, xl, xu):
    '''
    :param function_string: the function  formatted as a string
           You can get the value of the function by importing the  Function module
    :param xl: the lowerbound x
    :param xu: the upperbound x
    :return: the root of the equation or None if the method diverged
    '''
    formatter = Formatter()
    formatter.add_entry("Xl", "Xu", "F(Xl)", "F(Xu)", "Xr", "F(Xr)")
    func = Func(function_string)
    fl = func.get_value_at((xl))
    fu = func.get_value_at((xu))

    if ((fl < 0 and fu < 0) or ((fu > 0) and (fl > 0))):
        print(
            "Sorry but False_position method can not solve an equation with the given interval"
        )
        return None

    for i in range(0, constants.MAX_ITERATIONS):
        xrnew = (xl * fu - xu * fl) / (fu - fl)
        fr = func.get_value_at(xrnew)
        formatter.add_entry(xl, fl, xu, fu, xrnew, fr)
        if fr == 0:  # the exact root is found.
            print('exact root is found using false position ')
            formatter.display_steps()
            return xrnew
        elif fr * fl > 0:
            xl = xrnew
            fl = fr
        else:
            xu = xrnew
            fu = fr

        if (i > 0) and (abs(xrnew - xrold) < eps):
            print('False Position method has converged ')
            formatter.display_steps()
            return xrnew

        xrold = xrnew

    print(
        "The method diverged .Sorry but we can not solve this equation using False_position "
    )
    return None


#print(find_root_falsePosition("2*x**3 - 1" , -1 , 2))
# get_root_false_position()
    def __init__(self, parent, eqn, excution_time, left, right):
        self.parent = parent
        self.eqn = eqn

        large_font = ('Verdana', 10)

        equation_label = Label(parent,
                               text='the equation:',
                               bg='black',
                               fg='orange')
        equation_label.pack(fill=X, padx=5)
        eqn_text = Text(parent, bg='black', fg='white')
        eqn_text.insert(INSERT, self.eqn.replace('*', ''))
        eqn_text.config(state='disabled')
        eqn_text.pack(fill=X, padx=5)

        excution_time_label = Label(parent,
                                    text='excution time: ' +
                                    str(excution_time),
                                    bg='black',
                                    fg='orange',
                                    font=large_font)
        excution_time_label.pack(fill=X, padx=5)

        label = Label(parent,
                      text='Enter the value to be calculated!',
                      bg='black',
                      fg='orange')
        label.pack(fill=X, padx=5)

        self.entry = Entry(parent, font=large_font)
        self.entry.pack(fill=X, padx=5, pady=5)

        self.ans_label = Label(parent, bg='black', fg='white', font=large_font)
        self.ans_label.pack(fill=X, padx=5, pady=5)

        button = Button(parent,
                        text='calculate',
                        command=self.calculate,
                        bg='black',
                        fg='orange')
        button.pack(fill=X, padx=5, pady=5)

        self.func = Function(eqn)
        try:
            draw(eqn, left, right)
        except:
            print("can't draw!")
Example #6
0
def find_root_secant(function_string, x_prev=0, x_cur=1):
    """
    :param x_prev:
    :param x_cur:
    :param function_string: the function given in string format
    :return: the value at which the function is zero (if exists )
    """
    formatter = Formatter()
    formatter.add_entry("Xprev", "Xcur", "F(Xprev)", "F(Xcur)", "Xnext")

    fun = Func(function_string)
    found = False
    f_prev = (fun.get_value_at(x_prev))
    f_cur = (fun.get_value_at(x_cur))
    for i in range(0, constants.MAX_ITERATIONS):
        r = f_cur * ((x_cur - x_prev) / (f_cur - f_prev))
        x_next = (x_cur - r)

        formatter.add_entry(x_prev, x_cur, f_prev, x_cur, x_next)
        #print(x_prev, x_cur, f_prev, f_cur, x_next, sep=' <><><> ')

        if abs(r) < constants.EPS:
            found = true
            break

        x_prev = x_cur
        f_prev = f_cur
        x_cur = x_next
        f_cur = round(fun.get_value_at(x_cur))

    if found == false:
        print(
            "The method diverged , Try using another initial or make sure the function has a root and is continuous"
        )
        return None
    formatter.display_steps()
    return x_cur


#find_root_secant("exp(-x) - x " , 0 , 1 )
class queries():
    def __init__(self, parent, eqn, excution_time, left, right):
        self.parent = parent
        self.eqn = eqn

        large_font = ('Verdana', 10)

        equation_label = Label(parent,
                               text='the equation:',
                               bg='black',
                               fg='orange')
        equation_label.pack(fill=X, padx=5)
        eqn_text = Text(parent, bg='black', fg='white')
        eqn_text.insert(INSERT, self.eqn.replace('*', ''))
        eqn_text.config(state='disabled')
        eqn_text.pack(fill=X, padx=5)

        excution_time_label = Label(parent,
                                    text='excution time: ' +
                                    str(excution_time),
                                    bg='black',
                                    fg='orange',
                                    font=large_font)
        excution_time_label.pack(fill=X, padx=5)

        label = Label(parent,
                      text='Enter the value to be calculated!',
                      bg='black',
                      fg='orange')
        label.pack(fill=X, padx=5)

        self.entry = Entry(parent, font=large_font)
        self.entry.pack(fill=X, padx=5, pady=5)

        self.ans_label = Label(parent, bg='black', fg='white', font=large_font)
        self.ans_label.pack(fill=X, padx=5, pady=5)

        button = Button(parent,
                        text='calculate',
                        command=self.calculate,
                        bg='black',
                        fg='orange')
        button.pack(fill=X, padx=5, pady=5)

        self.func = Function(eqn)
        try:
            draw(eqn, left, right)
        except:
            print("can't draw!")

    def calculate(self):
        try:
            self.ans_label.configure(text=self.func.get_value_at(
                float(self.entry.get())),
                                     fg='orange')
        except:
            self.ans_label.configure(text='check you Entered valid value!',
                                     fg='red')


# o = Tk()
#
# queries(o,'x')
#
# o.mainloop()