Binary Search Problem 34- I need help with the functions logic

Back to General discussions forum

Chrisislearning     2025-01-24 17:40:18

I've build the code and I'm not sure how to change the logic here. Edit: I think the problem is with rounding but I don't know how to fix it.

    import math

def binary_search():
    A, B, C, D = 0.59912051, 0.64030348, 263.33721367, 387.92069617
    minimum = 0.0000001
    maximum = 100
    half = (maximum+minimum)/2
    x = round(half, 7)
    equation = A * x + B * math.sqrt(x ** 3) - C * math.exp(-x / 50) - D

    while equation > 0.0000001 or equation < -0.0000001:
        if equation < -0.0000001:
            minimum = half
        elif equation > 0.0000001:
            maximum = half

        half = round((maximum+minimum)/2, 7)
        x = round(half, 7)
        equation = round(A * x + B * math.sqrt(x ** 3) - C * math.exp(-x / 50) - D, 7)

        print("equation ",equation)
        print("minimum ",minimum)
        print("maximum ",maximum)
        print(x)

binary_search()

The function keeps going forever with

73.5953686
equation  5e-07
minimum  73.5953685
maximum  73.5953686
Chrisislearning     2025-01-24 19:01:25

Nevermind, solved it. I needed to not round anything except "equation".

Please login and solve 5 problems to be able to post at forum