Problem 34 Binary Search

Back to General discussions forum

Prabhat_SY     2020-11-09 18:28:27

I am not able to understand what we have to do in this question. Can anyone help me to understand the problem and how to approach it with python?

Igor Shapovalov     2020-11-09 20:49:57

You have to find x which will give correct equation. For simple example you have equation x-5=0, so you have to find x which will give 0, i.e. 5-5=0. About approach it looks like we have range 0-100, medium is 50, 50-5=45 it's more than 0. Next now we have range 0-50, and so on. Sorry for my bad english)

Prabhat_SY     2020-11-11 20:11:04

But how do I implement this thing in a code. This way I can get a single solution only

Igor Shapovalov     2020-11-12 02:32:51

"here A, B and C all would be positive so that function is monotonic. Solution is guaranteed to exist somewhere in range 0 <= x <= 100."

You have begin and end point begin=0, end=100. In the loop while begin < end you took middle i.e. begin+end/2, take result with whis x=middle,

if result more than 0 then end=middle-1, else begin=middle+1, and do it while you result!=0;

if you are asking about how to do loop:

in C++

    int input;

    cin>>input;

    for(int i=0;i< input;i++){
        int A,B,C;

        cin>>A>>B>>C;

        And here do binary search x 0-100 with A B C
    }
Alexandr Milovantsev     2020-11-12 04:16:03

Yes. But used function is monotonic (always increasing), so it have exactly one root.

Prabhat_SY     2021-06-19 12:27:39

import math n=int(input()) l=[] for _ in range(n): a,b,c,d=map(float,input().split()) mi=0 ma=100 while(mi<=ma): mid=(mi+ma)/2 x=mid f=ax + b math.sqrt(x ** 3) - c * math.exp( -x / 50) - d if (f>=0): mi=mid+1 else: ma=mid-1 l.append(mid) print(l)

qwerty     2021-06-19 17:20:49

It is not good to post solutions unless you made a private topic.

And it seems that your solution stops too early - this task require more precision. So I am not satisfied with your solution, anyway.

Prabhat_SY     2021-06-19 18:53:45

In this question we basically needed to do a binary search for finding the solution. I am doing it. The program also runs till completion but answer are not correct. The values which I need to put in the equation should be between 0 and 100 so are taken. Then why it stops early. And sorry for posting it here I don't know that we have a private option also.

qwerty     2021-06-19 19:34:09

Look, coding like this:

while(mi<=ma):
    ...

if (f>=0):
    mi=mid+1
else:
    ma=mid-1

...you in worst case get precision not better than 0.5 = 5e-1.

You need precision 0.0000001 = 1e-7 or better for this task.

Change code which sets new bounds. And maybe loop condition, too.

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