# --------------------------------------------------------------------------
# Name  : Sandeep Tripathi
# Branch: Mechanical Engineering
# Interval Halving Method
# --------------------------------------------------------------------------


print("------------------Interval Halving Method------------------\n")

# Define various modules required 
import math
from sympy import *
from sympy.parsing.sympy_parser import parse_expr

# Define the required function and its independent variable
x = Symbol("x")
funct = x * (x - 1.5)

# Input from the user lower interval, higher interval and desired accuracy 
low = float(raw_input("Enter the lower interval: "))
high = float(raw_input("Enter the higher interval: "))
acc = float(raw_input("Enter the desired accuracy: "))

# Checking whether the desired condition is satisfied
while (high - low) >= acc:
    # Splitting the interval in four parts
    interval = (high - low) / 4
    xmid = low + (2 * interval)
    x1 = low + interval
    x2 = low + (3 * interval)
    
    # Calculating the function at these intermediate points
    fmid = funct.evalf(subs={x:xmid})
    f1 = funct.evalf(subs={x:x1})
    f2 = funct.evalf(subs={x:x2})

    # Comparing the different functions
    if (f2 > fmid and fmid > f1):
        high = xmid
        xmid = x1
    if (f1 > fmid and fmid > f2):
        low = xmid
        xmid = x2
    if (f1 > fmid and f2 > fmid):
        low = x1
        high = x2

# Printing the results
print("The optimum point is " + str(xmid) + ".")
print("The value of function at optimum point is " + str(funct.evalf(subs={x:xmid})) + ".")




